Skip to content

Testing: What to Test and How, for Mid and Senior Engineers

The testing concepts interviewers probe: behaviour-focused tests, test levels, doubles, determinism, edge cases, real integrations, coverage and readability.

16 min read8 conceptsTechnical testsTesting: what to test and how

Testing questions in a technical interview are rarely about a framework's API. They check whether you can decide what deserves a test, at which level, with which dependencies replaced, and whether the result will still be trustworthy in a year. This guide covers the concepts behind strong answers. Each one has a short explanation, a TypeScript example using Vitest (the ideas carry over to any stack), and the traps that separate a mid-level answer from a senior one. The scenarios are invented: a coffee subscription, a clinic rota, an invoicing service, a parcel courier and an airline seat map. One idea runs through the whole guide. A good test fails when behaviour breaks and stays green when you only refactor. Use that as your yardstick for every choice.

Study order

If time is short, go in this order.

  1. Test observable behaviour, not implementation details

    It underpins every other answer. Interviewers listen for whether your tests survive refactoring.

  2. Choosing the right level: unit, integration, end-to-end

    Questions about what to test usually come down to picking the cheapest level that still proves the behaviour.

  3. Test doubles: stubs, fakes, spies and mocks, and when to use each

    Mocking judgement is the most common way to separate mid from senior candidates in testing discussions.

  4. Deterministic tests: controlling time, randomness and shared state

    Flaky test scenarios come up constantly, and fixing them shows practical production experience.

  5. Choosing cases: equivalence classes, boundaries and invalid input

    It gives you a systematic way to choose cases instead of guessing, which is easy to demonstrate live.

  6. Integration tests against real infrastructure

    It covers the bugs mocks cannot catch: SQL, constraints, serialisation and service contracts.

  7. Coverage is a map, not a goal: mutation testing

    A frequent trap question: knowing why coverage is not quality signals maturity.

  8. Readable tests: structure, naming and test data builders

    Polish that matters in code review and pairing exercises once the fundamentals are solid.

Test observable behaviour, not implementation details

A test is a specification of what the code promises to its callers: given these inputs, you get this output, this state change or this outgoing message. If your assertions depend on private methods, call order inside a class or internal data structures, every refactor breaks tests even when nothing visible has changed. Teams then learn to distrust red builds.

Ask what a caller can observe. For a pure function, that is the return value. For a service, it is the persisted state or the messages sent to other systems. Assert on those and leave the internals free to change.

In an interview, phrase it as resistance to refactoring. A test that fails during a pure refactor is a false positive. It costs time and teaches people to ignore failures. A test that passes while behaviour is broken is a false negative. Good tests minimise both.

TypeScript

import { describe, it, expect } from "vitest";

type Order = { bags: number; pricePerBagCents: number };

// Brewline coffee subscription: 10% off from the third bag.
export function totalCents(order: Order): number {
  const gross = order.bags * order.pricePerBagCents;
  return order.bags >= 3 ? Math.round(gross * 0.9) : gross;
}

describe("totalCents", () => {
  it("charges full price for two bags", () => {
    expect(totalCents({ bags: 2, pricePerBagCents: 1200 })).toBe(2400);
  });

  it("applies 10% off from the third bag", () => {
    expect(totalCents({ bags: 3, pricePerBagCents: 1200 })).toBe(3240);
  });
});

The tests describe pricing rules only. You could rewrite the discount logic entirely and they would stay valid.

Traps

  • Making private methods public, or exporting helpers, just so a test can call them. If a helper needs its own tests, it is probably a separate unit with its own public contract.
  • Asserting that an internal collaborator was called with exact arguments when the real outcome, a return value or a stored row, could be checked instead.
  • Snapshot-testing large objects or HTML, so every irrelevant change breaks the test and reviewers approve snapshot updates without reading them.

Choosing the right level: unit, integration, end-to-end

Unit tests are fast and pinpoint failures, but they cannot prove the pieces fit together. End-to-end tests prove the system works for a user, but they are slow, brittle and vague about what broke. Integration tests sit in between. The test pyramid is a cost heuristic: put most of the cases where they are cheapest, and use the expensive levels to check wiring and critical journeys.

The design move that makes this possible is separating decision logic from I/O. Keep business rules in pure functions or domain objects. Keep a thin shell that reads from the database, calls the rule and writes the result. You can then test the rules exhaustively in milliseconds and cover the shell with a few integration tests.

A senior answer ties the level to risk. Complex branching logic belongs in unit tests. SQL queries, serialisation and framework configuration belong in integration tests, because mocking them proves nothing. A small set of end-to-end tests protects the flows that would cost money or trust if they broke, such as sign-up or checkout.

TypeScript

import { it, expect } from "vitest";

// Rotaly clinic rota: a nurse cannot take overlapping shifts.
type Shift = { nurseId: string; start: Date; end: Date };

export function overlaps(a: Shift, b: Shift): boolean {
  return a.start < b.end && b.start < a.end;
}

export function canTakeShift(existing: Shift[], candidate: Shift): boolean {
  return !existing.some(
    (s) => s.nurseId === candidate.nurseId && overlaps(s, candidate)
  );
}

const shift = (nurseId: string, start: string, end: string): Shift => ({
  nurseId,
  start: new Date(start),
  end: new Date(end),
});

it("rejects a shift that overlaps by one minute", () => {
  const rota = [shift("n1", "2024-05-01T08:00Z", "2024-05-01T16:00Z")];
  expect(canTakeShift(rota, shift("n1", "2024-05-01T15:59Z", "2024-05-01T23:00Z"))).toBe(false);
});

it("allows back-to-back shifts", () => {
  const rota = [shift("n1", "2024-05-01T08:00Z", "2024-05-01T16:00Z")];
  expect(canTakeShift(rota, shift("n1", "2024-05-01T16:00Z", "2024-05-01T23:00Z"))).toBe(true);
});

it("ignores other nurses' shifts", () => {
  const rota = [shift("n2", "2024-05-01T08:00Z", "2024-05-01T16:00Z")];
  expect(canTakeShift(rota, shift("n1", "2024-05-01T10:00Z", "2024-05-01T12:00Z"))).toBe(true);
});

The overlap rule is pure, so it gets many cheap unit tests. One integration test is enough to check that the HTTP handler loads the rota and returns 409 when this returns false.

Traps

  • Testing rules only through the UI or HTTP layer, so every edge case costs seconds and a failure does not tell you which rule broke.
  • Unit-testing a repository by mocking the database driver. You end up verifying that you called the mock, not that the SQL is correct.
  • Treating the pyramid as a quota ("70% unit tests") instead of a cost and risk trade-off for the specific system.

Test doubles: stubs, fakes, spies and mocks, and when to use each

A stub returns canned answers to feed the code under test. A fake is a working but simplified implementation, such as an in-memory repository. A spy records calls so you can inspect them afterwards. A mock is a double you set expectations on, usually about outgoing calls. Interviewers expect you to know the terms, but they care more about your judgement.

A useful rule: use stubs or fakes for queries, the dependencies that give you data, and assert on outcomes. Use mocks or spies only for outgoing commands that cross a boundary you own the contract for, such as sending an email, publishing an event or charging a card. The side effect is the behaviour in those cases, so verifying the call is legitimate.

Do not double what you do not own without a wrapper. Wrap a third-party SDK in a small interface defined in your own terms, mock that interface in unit tests, and cover the wrapper with integration tests against the real service or its sandbox.

TypeScript

import { it, expect, vi } from "vitest";

// Ledgerly: email reminders for unpaid, overdue invoices.
interface Invoice { id: string; email: string; dueDate: Date; paid: boolean }
interface InvoiceRepo { unpaidDueBefore(date: Date): Promise<Invoice[]> }
interface Mailer { send(to: string, subject: string): Promise<void> }

class ReminderService {
  constructor(private repo: InvoiceRepo, private mailer: Mailer) {}

  async run(now: Date): Promise<number> {
    const overdue = await this.repo.unpaidDueBefore(now);
    for (const inv of overdue) {
      await this.mailer.send(inv.email, `Invoice ${inv.id} is overdue`);
    }
    return overdue.length;
  }
}

// Fake: real filtering logic, in memory.
class InMemoryInvoiceRepo implements InvoiceRepo {
  constructor(private invoices: Invoice[]) {}
  async unpaidDueBefore(date: Date): Promise<Invoice[]> {
    return this.invoices.filter((i) => !i.paid && i.dueDate < date);
  }
}

it("emails only unpaid, overdue invoices", async () => {
  const repo = new InMemoryInvoiceRepo([
    { id: "A1", email: "a@x.test", dueDate: new Date("2024-03-01"), paid: false },
    { id: "B2", email: "b@x.test", dueDate: new Date("2024-03-01"), paid: true },
    { id: "C3", email: "c@x.test", dueDate: new Date("2024-04-01"), paid: false },
  ]);
  const mailer = { send: vi.fn().mockResolvedValue(undefined) }; // spy on an outgoing command

  const sent = await new ReminderService(repo, mailer).run(new Date("2024-03-15"));

  expect(sent).toBe(1);
  expect(mailer.send).toHaveBeenCalledTimes(1);
  expect(mailer.send).toHaveBeenCalledWith("a@x.test", "Invoice A1 is overdue");
});

A fake for the data source and a spy for the email, because sending the email is the behaviour under test.

Traps

  • Mocking every collaborator by default. Tests then mirror the implementation line by line and break on every refactor.
  • Verifying calls to query dependencies ("repo.find was called once") instead of checking the result the code produced from that data.
  • Letting a fake drift from the real implementation. Run the same contract test suite against both so they agree on behaviour.
  • Mocking a third-party library's types directly, which ties your tests to its internals and hides breaking changes on upgrade.

Deterministic tests: controlling time, randomness and shared state

A flaky test passes and fails without any code change. The usual causes are the real clock, random values, ordering assumptions (hash maps, parallel tests, unsorted query results), shared mutable state between tests, and fixed sleeps that wait for async work. Flaky tests are worse than missing ones, because they train the team to rerun until green.

Treat non-determinism as a dependency and inject it. Pass now as a parameter or inject a clock. Inject a seeded random generator or an ID factory. When you cannot change the signature, use fake timers to pin the system time. For async work, wait on a condition or an awaited promise, never a fixed delay.

Isolation matters just as much. Each test should create the data it needs and not rely on another test having run first. Reset fake timers, environment variables and module-level singletons after each test, and make sure the suite passes in random order and in parallel.

TypeScript

import { it, expect, vi, afterEach } from "vitest";

const FOURTEEN_DAYS_MS = 14 * 24 * 60 * 60 * 1000;

export function isTrialActive(startedAt: Date, now: Date = new Date()): boolean {
  return now.getTime() - startedAt.getTime() < FOURTEEN_DAYS_MS;
}

afterEach(() => {
  vi.useRealTimers();
});

it("ends the trial exactly 14 days after start", () => {
  const start = new Date("2024-06-01T00:00:00Z");
  expect(isTrialActive(start, new Date("2024-06-14T23:59:59Z"))).toBe(true);
  expect(isTrialActive(start, new Date("2024-06-15T00:00:00Z"))).toBe(false);
});

it("falls back to the system clock", () => {
  vi.useFakeTimers();
  vi.setSystemTime(new Date("2024-06-10T00:00:00Z"));
  expect(isTrialActive(new Date("2024-06-01T00:00:00Z"))).toBe(true);
});

Injecting now makes the boundary test trivial. Fake timers cover the default path without depending on the day the suite runs.

Traps

  • Using setTimeout or sleep(500) to wait for async work. It is slow when the work is fast and flaky when CI is slow.
  • Forgetting to restore fake timers or mocked globals, which leaks state into unrelated tests and produces order-dependent failures.
  • Asserting on the order of results from a query without ORDER BY, or from iterating a set or map whose order your logic does not guarantee.
  • Quarantining flaky tests and never coming back to them. Track them and fix the root cause, which is often a real race condition in production code.

Choosing cases: equivalence classes, boundaries and invalid input

You cannot test every input, so split the input space into equivalence classes: ranges where the code should behave the same way. Pick one representative per class, then add the values on each side of every boundary, because off-by-one errors live there. Add the invalid classes too: zero, negatives, empty collections, null or undefined, non-integers, very large values and duplicates.

Table-driven tests (it.each in Vitest and Jest, parametrised tests elsewhere) keep this compact and make missing cases easy to spot in review. Each row reads as one rule of the specification.

For logic with many interacting inputs, such as parsers, serialisers or sorting, property-based testing complements examples. Instead of fixed cases, you state invariants, for example that decoding an encoded value returns the original, and let a library generate hundreds of inputs and shrink any failure to a minimal case.

TypeScript

import { it, expect } from "vitest";

// Parcelo courier: fee tiers by weight in grams.
export function shippingFeeCents(grams: number): number {
  if (!Number.isInteger(grams) || grams <= 0) {
    throw new RangeError("weight must be a positive integer");
  }
  if (grams <= 2000) return 499;
  if (grams <= 10000) return 999;
  return 1999;
}

it.each([
  [1, 499],
  [2000, 499],
  [2001, 999],
  [10000, 999],
  [10001, 1999],
])("%i g costs %i cents", (grams, fee) => {
  expect(shippingFeeCents(grams)).toBe(fee);
});

it.each([0, -5, 1.5, Number.NaN])("rejects %s grams", (grams) => {
  expect(() => shippingFeeCents(grams)).toThrow(RangeError);
});

Five rows cover three valid classes and both boundaries. Four rows cover the invalid classes.

Traps

  • Testing only the happy path with round numbers like 500 g and 5000 g, which never touch a boundary.
  • Writing many cases from the same equivalence class. They add run time and maintenance without adding confidence.
  • Computing the expected value in the test with the same formula as the production code. Hard-code expected values you worked out independently.

Integration tests against real infrastructure

Some behaviour exists only in the infrastructure: unique constraints, transaction isolation, query plans, JSON column handling, message broker acknowledgements. Mocks cannot reproduce any of it. For these, run the real thing, ideally the same engine and major version as production, started in a container for the test run.

Keep these tests focused on the adapter. A repository test checks that its SQL does what the domain expects, including constraint violations and concurrency cases. It does not re-test business rules that already have unit tests. Isolate tests by truncating tables, using unique keys per test, or wrapping each test in a transaction that rolls back, provided the code under test does not manage its own transactions.

When two services talk over HTTP or a queue, consumer-driven contract tests check that the provider still satisfies what each consumer relies on, without deploying both sides together. They catch the classic failure where both services have green unit tests and still disagree about a field name.

TypeScript

import { beforeAll, afterAll, it, expect } from "vitest";
import { PostgreSqlContainer, StartedPostgreSqlContainer } from "@testcontainers/postgresql";
import { Client } from "pg";

let container: StartedPostgreSqlContainer;
let db: Client;

beforeAll(async () => {
  container = await new PostgreSqlContainer("postgres:16").start();
  db = new Client({ connectionString: container.getConnectionUri() });
  await db.connect();
  await db.query(
    "CREATE TABLE seats (flight TEXT, seat TEXT, passenger TEXT, UNIQUE (flight, seat))"
  );
}, 60_000);

afterAll(async () => {
  await db.end();
  await container.stop();
});

it("refuses to double-book a seat", async () => {
  await db.query("INSERT INTO seats VALUES ($1, $2, $3)", ["SK101", "12A", "Ines"]);

  await expect(
    db.query("INSERT INTO seats VALUES ($1, $2, $3)", ["SK101", "12A", "Omar"])
  ).rejects.toMatchObject({ code: "23505" }); // unique_violation
});

Only a real Postgres can prove that the unique constraint stops a double booking. A mocked client would happily accept both inserts.

Traps

  • Using an in-memory database such as SQLite in tests while production runs Postgres or MySQL. Dialect, locking and constraint behaviour differ.
  • Sharing one database across tests without cleanup, so results depend on execution order.
  • Starting a fresh container per test instead of per suite, which turns a seconds-long run into minutes.
  • Pointing integration tests at a shared staging environment that other people change underneath you.

Coverage is a map, not a goal: mutation testing

Line and branch coverage tell you which code ran during the tests, not whether any test would notice if it were wrong. A test with no assertions can reach full line coverage. That makes coverage useful for finding untested areas and useless as proof of quality. Once it becomes a target, people write tests to move the number.

Mutation testing measures what coverage cannot. A tool such as Stryker makes small changes to your code (flipping <= to <, negating a condition, replacing a return value) and reruns the tests. If the tests still pass, the mutant survived, and you have found a behaviour nobody verifies. It is expensive, so teams usually run it on critical modules or on changed files only.

In an interview, a strong answer sounds like this: coverage helps me spot untested risky code, and I review low coverage in changed files during code review. I do not enforce a global percentage, because a high number does not prove that the important behaviour has assertions.

TypeScript

import { it, expect } from "vitest";

export function canRefund(daysSincePurchase: number, used: boolean): boolean {
  return daysSincePurchase <= 30 && !used;
}

// Full line and statement coverage, zero protection:
// a mutant that changes <= to < would survive.
it("runs canRefund", () => {
  canRefund(10, false);
  canRefund(40, true);
});

// Kills the boundary mutant and the negation mutant.
it("allows refunds up to and including day 30 for unused items", () => {
  expect(canRefund(30, false)).toBe(true);
  expect(canRefund(31, false)).toBe(false);
  expect(canRefund(30, true)).toBe(false);
});

Both tests execute every line. Only the second one would fail if the refund rule changed.

Traps

  • Enforcing a global coverage threshold. It encourages assertion-free tests of trivial code while complex logic stays weakly verified.
  • Assuming 100% branch coverage means every combination of conditions was tested. Branch coverage does not cover combinations of conditions.
  • Trying to kill every mutant, including equivalent mutants that do not change behaviour. Use mutation scores to guide you, not as another target.

Readable tests: structure, naming and test data builders

Tests are the documentation that cannot go stale, so they should read like specifications. Use the Arrange, Act, Assert structure, with one behaviour per test. Name the test after the rule, not the method: "grants late checkout to gold members" tells a reader far more than "testLateCheckout2".

Keep only the relevant details visible. If a booking needs eight fields but the rule depends on two, a test data builder supplies sensible defaults and lets each test override what matters. Readers then see exactly which inputs drive the outcome, and adding a required field to the model changes one builder instead of fifty tests.

Avoid logic in tests: no loops, conditionals or computed expectations, apart from table-driven cases. Prefer some duplication in tests over clever shared helpers that hide what is being checked. When a test fails, the failure message and the test body should be enough to understand what broke, without opening the production code.

TypeScript

import { it, expect } from "vitest";

type Booking = {
  guestName: string;
  nights: number;
  roomType: "single" | "double";
  loyaltyTier: "none" | "gold";
};

function aBooking(overrides: Partial<Booking> = {}): Booking {
  return { guestName: "Test Guest", nights: 2, roomType: "double", loyaltyTier: "none", ...overrides };
}

export function lateCheckoutAllowed(b: Booking): boolean {
  return b.loyaltyTier === "gold" || b.nights >= 5;
}

it("grants late checkout to gold members regardless of stay length", () => {
  // Arrange
  const booking = aBooking({ loyaltyTier: "gold", nights: 1 });
  // Act
  const allowed = lateCheckoutAllowed(booking);
  // Assert
  expect(allowed).toBe(true);
});

it("refuses late checkout for short stays without loyalty status", () => {
  expect(lateCheckoutAllowed(aBooking({ nights: 4 }))).toBe(false);
});

The builder hides irrelevant fields, so each test shows only the inputs that decide the outcome.

Traps

  • Large shared fixtures in beforeEach that every test mutates a little, so no single test shows its own setup.
  • Several unrelated behaviours checked in one test. The first failing assertion hides the rest and the name cannot describe them all.
  • Builder defaults that quietly trigger the rule under test, for example a default of 5 nights, which makes a gold-member test pass for the wrong reason.

Common questions

Short answers to the usual doubts.

Should I always write tests first (TDD)?

Treat TDD as a tool, not a creed. Writing the test first works well when the behaviour is clear and the logic is non-trivial, because it pushes you towards small, injectable designs. For exploratory spikes or UI layout, you can write tests after the design settles. In an interview, show that you know the trade-off and that every behaviour change ships with a test that would have failed without it.

How do I test code that has no seams, like a class that creates its own database client?

Start with a characterisation test at the highest level you can run reliably, to pin down current behaviour. Then introduce a seam: pass the dependency through the constructor, extract the decision logic into a pure function, or wrap the static call behind an interface. Once the seam exists, add focused unit tests and keep the broad test as a safety net while you refactor.

What should I do when a bug reaches production?

Write a test that reproduces the bug before fixing it, at the lowest level that can express it, and confirm it fails. Then fix the code and watch the test pass. Also ask why the existing tests missed it, for example a missing boundary, a mocked dependency hiding real behaviour or an untested integration, and close that gap more broadly if it is systemic.

Are end-to-end tests worth their cost?

Yes, for a small number of critical journeys where a failure is expensive and only the full stack can prove things work, such as sign-up, payment or the core workflow. Keep them few, make them independent of each other, give them stable selectors and their own test data, and do not use them to cover edge cases that a unit test can check in milliseconds.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide2 of 2 · Quality and operationsDevOps Interview Guide: Deploying and Operating in ProductionRead the next one