Skip to the content

Lesson 271 of 296

The testing pyramid, mocking, and coverage vs confidence

What you will learn

  • Why we test, and what good tests look like
  • The testing pyramid and the testing trophy
  • Test doubles: dummies, stubs, spies, mocks and fakes
  • When mocking helps and when it hurts
  • Code coverage: what it measures and what it does not
  • Flaky tests
On this page

Why test?

Tests let a team change code confidently: they catch regressions within minutes, document how the code should behave, and make refactoring safe. Good tests are:

PropertyMeaning
FastRun on every save and every pull request
DeterministicSame result every time (no real time, randomness, network)
IndependentNo test depends on another or on run order
ReadableArrange, Act, Assert; a clear name saying the behaviour: rejects orders with zero quantity
Behaviour-focusedTest what the code does, not how it does it, so refactoring does not break tests
TrustworthyA failing test means a real problem

The testing pyramid

        /  E2E  \          few: slow, broad, most realistic
       /---------\
      / Integration\       some: components working together
     /-------------\
    /     Unit      \      many: fast, focused
  • Unit tests: single functions or classes, dependencies replaced; milliseconds each.
  • Integration tests: several real parts together (API + database, component + mocked network); seconds.
  • End-to-end tests: the real system through the UI or public API (Lessons 186 and 206); slowest and most brittle, so keep them for critical journeys.

The testing trophy (popular in front-end work) puts the biggest share in integration tests, plus static analysis (TypeScript, ESLint) at the base, because integration tests give the most confidence per test for UI code. The shared message: many cheap tests, fewer expensive ones, and choose the level that gives confidence for each risk.

Test doubles

A test double stands in for a real dependency:

DoubleWhat it doesExample
DummyPassed but never usedA logger argument required by a constructor
StubReturns fixed answersA clock that always returns 2026-01-01
SpyRecords how it was called (may also call through)vi.spyOn(mailer, "send")
MockPre-programmed with expectations about calls; the test fails if they are not metexpect(gateway.charge).toHaveBeenCalledWith("c1", 500)
FakeA working lightweight implementationAn in-memory repository (Lesson 270)

In everyday speech people call all of these "mocks".

When mocking helps, and when it hurts

Mock at the boundaries you do not control or that are slow or non-deterministic: network APIs, payment providers, email, time, randomness, file systems.

Over-mocking hurts:

  • Tests that mock every collaborator mostly test the mocks, and pass even when the real pieces do not fit together.
  • Tests that verify internal call sequences break on every refactor, even when behaviour is unchanged.
  • Mocks drift from reality when the real dependency changes.

Prefer real objects for your own pure logic, fakes for repositories, test databases for data access (Lesson 206), and MSW for HTTP (Lesson 185). Assert on outcomes (the returned value, the saved state, the HTTP response) more than on calls; check calls only when the call is the outcome (an email must be sent, a payment must be charged once).

Code coverage

Coverage measures which code the tests executed:

MetricCounts
Line / statement coverageLines or statements that ran
Branch coverageEach side of every if, ?:, && that ran
Function coverageFunctions called

Tools: Vitest and Jest with V8 or Istanbul (vitest --coverage).

Coverage is not confidence. A test can execute every line and assert nothing:

TypeScript
export function vatPence(netPence: number): number {
  if (netPence < 0) throw new Error("Net amount cannot be negative");
  return Math.round(netPence * 0.2);
}

A test that calls vatPence(1000) and vatPence(-1) inside a try with no assertions gives 100% line and branch coverage (measured with Vitest's V8 coverage: 100% of statements, branches, functions and lines), yet would still pass if the function returned the wrong number. Useful views of coverage:

  • Low coverage reliably shows untested code; high coverage does not prove the tests are good.
  • Use it to find important untested branches (error paths, permission checks), not as a target to game. A sensible team floor (say 70 to 80% on business logic) can stop regressions in coverage without encouraging meaningless tests.
  • Mutation testing (Stryker) measures test quality: it makes small changes to the code ("mutants", such as changing < to <= or 0.2 to 0) and checks that some test fails. Surviving mutants reveal weak tests. Against the assertion-free test above, every mutant survives; with real assertions, they are killed.

Flaky tests

A flaky test sometimes passes and sometimes fails without code changes. Causes: real time and timers, random data, shared state between tests, test order, real network calls, race conditions, fixed sleeps in E2E tests (Lesson 186). Flaky tests destroy trust ("just re-run it"); fix or quarantine them quickly. Inject clocks and random sources, isolate data, and wait for conditions instead of sleeping.

How to say it in an interview

"Tests let us change code safely, so I keep them fast, deterministic, independent and focused on behaviour. I follow the pyramid, or for front ends the trophy: many unit and integration tests and a few end-to-end tests for critical journeys. I use test doubles at the boundaries: stubs for time, fakes for repositories, MSW for HTTP, and real implementations for my own logic, asserting outcomes rather than internal calls so refactors do not break tests. Coverage shows what is untested but not whether tests are meaningful, since a test without assertions can reach 100%, so I focus on important branches and use mutation testing to judge quality, and I fix flaky tests quickly."

Key words

WordMeaning
Testing pyramid / trophyModels for how many tests to write at each level
Test doubleAny stand-in for a real dependency
Stub / spy / mock / fakeFixed answers / records calls / expects calls / working light version
Code coverageShare of code executed by tests
Branch coverageShare of decision outcomes executed
Mutation testingChanging code to see whether tests catch it
Flaky testA test with inconsistent results

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.