Skip to content

Testing Strategy ​

Decide what to test at which layer, then keep the suite fast and honest enough that people still run it a year later.

In this chapter: the four layers and what each costs · pyramid against trophy · test doubles · what coverage does and does not tell you · why suites get abandoned

💡 The Core Idea ​

A test suite is a budget, not a virtue. Every test costs runtime on every push and maintenance on every refactor. In return it buys some confidence. Strategy is deciding which tests are worth their price.

Teams get this wrong in two mirror-image ways. One team writes thousands of unit tests that assert on internals. Every refactor breaks a hundred tests, and nobody learns whether the product works. The other writes only end-to-end tests. The suite takes forty minutes, fails randomly twice a week, and gets skipped. Both end up with a suite nobody trusts, and that is the same as no suite.

So the useful question is never "are we testing enough". It is at which layer does this particular risk get caught most cheaply.

How It Works ​

Four layers, four price tags ​

LayerScopeSpeedCatchesBreaks when
StaticTypes and lintInstantWrong shapes, missing casesRarely — it is the cheapest layer
UnitOne functionMillisecondsLogic and edge casesYou change the function's internals
Component/integrationA flow with a faked networkUnder a secondWiring, state, user-visible behaviourThe user-visible behaviour changes
End-to-endThe real app in a real browserSeconds to minutesEverything the other layers fakeAnything at all — including nothing

The compiler is the layer people forget to count. A prop contract checked by tsc needs no test at all. A hundred type-level guarantees cost nothing per push. A test that checks something the type system already proves is pure overhead.

Choosing a layer:

text
Pure logic or a calculation?      → unit
Wiring, state, or what a user sees? → component/integration
A journey that loses money if broken? → end-to-end
A data shape or a contract?         → the type checker

For the React version of that decision (component, renderHook or a real build), see Writing the Tests: Vitest and React Testing Library.

Pyramid against trophy ​

Both shapes say "more of the cheap layers, fewer of the expensive ones". They disagree about where the middle sits.

PyramidTrophy
WeightingMostly unit, some integration, few E2EMostly integration, then unit, then static, few E2E
AssumesThe risk is in the logicThe risk is in the wiring
FitsPricing engines, parsers, data pipelinesUI-heavy products where interaction is the behaviour

For a frontend the trophy is usually right, and you should be able to say why. A typical React application has little logic and a great deal of wiring. The bugs are in the loading state that never clears, the form that submits twice, the error path nobody rendered. All three are integration-level failures, and a unit test of a reducer cannot see them.

Test doubles, and which one you actually want ​

A double stands in for a real dependency. Interviewers often ask about the vocabulary. The difference that matters is whether the double verifies how it was called.

DoublePurposeVerifies calls
StubReturns canned data so the test can proceed❌
SpyWraps a real function and records calls✅
MockA double with expectations you assert on✅
FakeA working simplified implementation — an in-memory store❌

The rule that prevents most bad tests: double the things you do not own. The network, the clock, randomness, a payment gateway. Doubling your own components, hooks and utilities turns an integration test into a test of the mocks. It passes happily while the real integration is broken.

Coverage measures execution, not correctness ​

Coverage tells you which lines ran. It cannot tell you whether an assertion would have caught a bug.

typescript
function divide(a: number, b: number): number {
  return a / b;
}

it("divides", () => {
  expect(divide(10, 2)).toBe(5); // 100% line coverage
});
// divide(10, 0) returns Infinity and is never tested.

Branch coverage is the more useful number, because it names untaken paths, not unexecuted lines. Use either as a finder: "which error paths has nobody tested?" Never use it as a target. The cheapest way to meet a coverage target is to test trivial code.

⚠️ A coverage threshold in CI reliably produces tests written to raise the number. If you want a quality signal, not an execution count, mutation testing is the honest one. See End-to-End, Visual and Contract Testing with Playwright.

The four causes of a flaky test ​

A flaky test passes and fails without a code change. It does more damage than a missing test, because it teaches the team to re-run the pipeline instead of reading the failure.

CauseThe flaky versionThe fix
TimingA fixed setTimeout before assertingawait screen.findBy..., which waits exactly as long as needed
Shared stateA module-level object two tests mutateA factory that returns fresh data per test
Real networkA live API callRequest interception — see Frontend Integration Testing
RandomnessMath.random(), Date.now()Seed it, or freeze the clock with vi.setSystemTime()
typescript
// ❌ Arbitrary wait — passes locally, fails on a loaded CI runner
setTimeout(() => expect(screen.getByText("Saved")).toBeInTheDocument(), 1000);

// ✅ Waits for the condition, not for the clock
expect(await screen.findByText("Saved")).toBeInTheDocument();

Every test must pass on its own and in any order. Isolation is not a nicety. A suite whose tests depend on execution order cannot run in parallel, and that makes it slow enough to skip.

When to Use It ​

SituationTest atWhy
A currency formatter with twelve edge casesUnitA hundred cases cost nothing
A form that validates, submits and shows an errorIntegrationThis is where the real bugs are
Login, checkout, signupEnd-to-end, and only theseFailure costs money; slowness is acceptable for three tests
A prop or API response shapeThe type checkerAlready free on every build
A design token or spacing changeVisual regression, not an assertionYou cannot assert your way to "looks right"
A bug just reported in productionA failing unit or integration test firstIt proves the fix and stops the regression

Common Mistakes ​

❌ Testing implementation details. Asserting on internal state or on a hook's return value means every refactor breaks tests while behaviour is unchanged. ✅ Assert what the user can observe. The test then fails only when something real breaks.

❌ Over-mocking. Replacing your own components and utilities produces a test of the doubles. ✅ Double the network, the clock and third parties. Keep everything you own real.

❌ A coverage threshold as the quality gate. It is satisfied by testing getters. ✅ Use coverage to find untested branches, and gate on the suite passing instead.

❌ Tolerating a flaky test. One flake teaches everyone to re-run the pipeline. The whole suite then stops working as a signal. ✅ Fix it or quarantine it the same day. Treat the flake as a bug with a cause.

❌ Deep describe nesting and vague names. it("works") inside four blocks tells you nothing when it fails at 2am. ✅ One or two levels, and a name stating condition and expected result.

🔑 Key Takeaways ​

  • A test suite is a budget: each layer has a price, and strategy is spending it where risk is cheapest to catch.
  • The type checker is a testing layer, and the cheapest one — do not test what it already proves.
  • For UI-heavy frontends the trophy shape wins, because the bugs are in wiring rather than logic.
  • Double only what you do not own; doubling your own code tests the doubles.
  • Coverage measures which lines ran, never whether a bug would be caught.

Interview Questions ​

Q: How do you decide whether something gets a unit test or an integration test?

By asking where the risk actually is. Pure logic with many edge cases is cheapest to cover as a unit test, because a hundred cases run in milliseconds. Wiring bugs only show up when the pieces run together: state that does not clear, an error path nobody rendered, a request fired twice. So they belong at the integration layer. In a typical React app that is most of the risk. That is why the integration layer gets the most weight.

Q: Your suite takes 25 minutes and people are merging without it. What do you do?

Find out where the time goes first. The answer is almost always a handful of end-to-end tests covering things an integration test could catch. Push those down a layer. Keep E2E for the journeys whose failure costs money. Make sure the rest can run in parallel, which usually means fixing shared state. Fast and trusted beats thorough and skipped.

Q: Is 100% coverage worth aiming for?

No, and not because the last stretch is hard. Coverage counts executed lines, not caught bugs. A test with no meaningful assertion raises coverage and catches nothing. A threshold in CI reliably produces exactly those tests. Coverage is useful for finding untested error paths. Mutation testing is the metric that actually measures whether tests would catch a defect.

Q: When would you not write a test?

When the type checker already proves it, or when the assertion would restate the implementation. Also when the thing is genuinely visual: "the spacing looks right" is a visual regression job, not an assertion. The same goes for throwaway code with a known short life. Saying so honestly is better than pretending to a standard nobody will maintain.

The whole book, free to read. Generated from the manuscript on every change.

Your progress

Tick each chapter in the sidebar once you have read and understood it. Your name and email keep the ticks on any device.

Your name and email are stored to save your progress. Nothing else is done with them.