Skip to content
FrontDepth, Home

Testing

What to test, and at which level

What tests are for and at which level to write them: unit, integration and end-to-end tests and what each costs, the test pyramid and the testing trophy, testing behaviour instead of implementation details, what to leave untested, what code coverage measures, and regression tests in CI and code review.

JuniorMiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

Before you start

No prerequisites.

This topic starts at Junior level.

JuniorConcept

Why write tests

A test is code that runs a piece of your code and checks the result automatically. You write it once, and a test runner such as Vitest runs it again after every change, in seconds, the same way every time.

TypeScript
import { expect, test } from "vitest";
import { cartTotal } from "./cart";

test("adds up price times quantity", () => {
  const items = [
    { price: 4, quantity: 2 },
    { price: 10, quantity: 1 },
  ];
  expect(cartTotal(items)).toBe(18);
});

Save it as cart.test.ts next to cart.ts, install Vitest (npm install -D vitest) and run npx vitest. Vitest finds files named *.test.* or *.spec.*, runs every test in them and reports which ones failed. expect(value).toBe(18) is an assertion: if the value is not 18, it throws, and the test fails. On your machine Vitest then keeps watching and reruns the tests when you save a file; in CI it runs once and exits.

What tests give you

  • Confidence to change code. Without tests, every refactor, dependency upgrade or bug fix means clicking through the app by hand and hoping you checked the right screens. With tests, the runner tells you within seconds whether the behaviour you care about still holds. Martin Fowler's test for "enough tests" is exactly this: bugs rarely escape into production, and you are rarely afraid to change code.
  • A specification of behaviour. "adds up price times quantity" plus its example is documentation that can't silently go out of date: if the behaviour changes, the test fails. A new teammate can read the test file to learn what the module promises.
  • Faster feedback than checking by hand. A unit test runs in milliseconds. Checking the same rule in the browser takes a minute, and nobody does it for every edge case after every change.
  • A signal about design. A function that reads the clock, calls the network and computes a price at once is hard to test, and just as hard to reuse. Writing the test shows that early.

What tests don't give you

Tests show that the cases you wrote behave as you expected; they don't prove the code has no bugs. A test that checks the wrong thing, or nothing at all, is just as green as a good one. A test fails only when an assertion (or anything else) throws, so a test with no assertions passes as long as the code doesn't crash. That is why the rest of this topic is about which tests to write and where, not about how many.

JuniorConcept

Unit, integration and end-to-end tests

Tests differ in how much of the system they run at once. The usual names are three levels:

  • A checks one small piece of logic on its own: a function, a hook, a reducer. Cheap collaborators (a pure helper) stay real; slow or uncontrollable ones (the network, the clock) are replaced.
  • An checks that several pieces work together: a form with its validation and its API client, a page component with its real children. In frontend work this often means rendering a component tree in a simulated DOM and replacing only the network.
  • An runs the real, built app in a real browser against a real or realistic backend, and acts like a user: open the page, type, click, check what appears. Playwright and Cypress are the common tools.
UnitIntegrationEnd-to-end
Typical run timemillisecondstens to hundreds of msseconds
Catcheslogic errors, edge casesparts that disagree: props, field names, call orderbroken routing, build, config, browser-only bugs
Points to the bugpreciselyroughlyrarely
Fails for reasons outside your codealmost neverseldomoften: network, test data, timing

What each level costs

Speed is only part of the price. Higher-level tests are slower and harder to set up, but the bigger cost is noise: an end-to-end test can fail because a test server was slow, a seeded record was missing or an animation was still running. A test that sometimes fails without any change to the code is a , and every one teaches the team to ignore red builds.

Lower-level tests have the opposite weakness: they are fast and precise, but they can all pass while the product is broken. Each unit can be correct on its own while two of them disagree, for example the form sends { qty } and the API client reads quantity. Only a test that runs both together notices.

The same change hits the levels differently: rename an internal helper, and the unit tests that call it break while end-to-end tests don't notice; break the checkout button's wiring, and every unit test stays green. A good suite mixes levels so that each kind of mistake is caught by at least one test, as cheaply as possible.

The names are not precise. Whether a "unit" is one function or a module with its helpers differs between teams; Martin Fowler calls it "a situational thing". What matters is that a team agrees.

JuniorConcept

Arrange, act, assert

Most good tests have the same three steps, which Bill Wake named Arrange, Act, Assert:

TypeScript
import { describe, expect, test } from "vitest";
import { applyCoupon } from "./coupon";

describe("applyCoupon", () => {
  test("takes 10% off with SAVE10", () => {
    // Arrange: the input
    const order = { subtotal: 200, coupon: "SAVE10" };

    // Act: one call to the code under test
    const result = applyCoupon(order);

    // Assert: the result the caller sees
    expect(result.total).toBe(180);
  });

  test("rejects an expired coupon", () => {
    const order = { subtotal: 200, coupon: "SUMMER23" };
    expect(() => applyCoupon(order)).toThrow("Coupon has expired");
  });
});
  • Arrange builds the situation: inputs, test data, replacements for dependencies.
  • Act does one thing: calls the function, dispatches the action, clicks the button.
  • Assert checks what the caller can observe: a return value, an error, what is on the screen, what was sent.

Behaviour-Driven Development uses the same shape under the names Given, When, Then (from Daniel Terhorst-North and Chris Matts), and Gerard Meszaros calls it the Four-Phase Test, with a fourth step, teardown, that cleans up. Martin Fowler describes them as the same pattern.

Names

A test name states one behaviour, so that a failure reads like a broken promise: applyCoupon > rejects an expired coupon. Avoid names that describe the code (calls validateDate) or say nothing (works, test 2). If a name needs "and", it is probably two tests.

Habits that keep tests honest

  • One reason to fail. Several expect calls are fine when they describe one outcome, such as the total and the discount line of the same order. A test that checks ten unrelated things fails for ten reasons, and its name can't describe them.
  • Literal expected values. Write toBe(180), not toBe(200 - 200 * 0.1) or a call to the helper the code itself uses: a test that computes the answer the same way repeats the bug.
  • No logic in the test. Loops and if in a test body make it a second program that can be wrong. For many similar cases, use a table of inputs with test.each.
  • See it fail once. Before you trust a new test, break the code on purpose, or run the test before the fix, and watch it go red. A test that has never failed may not be testing anything.
MiddleConcept

The test pyramid and the testing trophy

How many tests of each level should a project have? Two well-known models answer differently. Both are opinions about return on investment, not laws.

The test pyramid. Mike Cohn described the "Test Automation Pyramid" in Succeeding with Agile (2009), and Martin Fowler's article on it (2012) gives the reasoning: many fast unit tests at the base, fewer tests through a service layer, very few UI tests at the top, because tests that run end-to-end through the UI are "brittle, expensive to write, and time consuming to run". Ham Vocke's The Practical Test Pyramid (martinfowler.com, 2018) sums it up in two rules: write tests with different granularity, and the more high-level you get, the fewer tests you should have.

The testing trophy. Kent C. Dodds drew the "Testing Trophy" for JavaScript applications (2018): static analysis at the bottom, then unit, integration as the biggest part, and end-to-end on top. Integration tests, he argues, "strike a great balance on the trade-offs between confidence and speed/expense", so most (not all) effort should go there. Behind it is his principle, which is also Testing Library's guiding principle: "The more your tests resemble the way your software is used, the more confidence they can give you."

Text
                pyramid (Cohn)     trophy (Dodds)
fewest          UI / E2E           end-to-end
                service            integration (most effort)
most            unit               unit
underneath      -                  static: types, lint

Static analysis is the base. Dodds added it because in JavaScript it is not a given; it catches "typos and type errors as you write the code". Strict TypeScript and ESLint check every line before any test runs, almost for free. Don't spend tests on what the type checker proves (that cartTotal returns a number); spend them on what types can't see (that it returns the right number).

Where the models agree

Fowler pointed out (2021) that much of the debate is about what "unit test" means. A test that renders a component with its real children is a sociable unit test to some (Jay Fields' term, the opposite of a solitary test that replaces collaborators with doubles) and an integration test to others. Both models agree that most tests should be fast and deterministic, that end-to-end tests are the most expensive kind and belong to the critical journeys, and that a test earns its place by the confidence it gives per minute spent writing, running and maintaining it.

For a React app this means many fast tests that render components with their real children and fake only the network, unit tests for heavy logic (parsing, pricing, dates), and a few end-to-end tests for flows that must never break.

MiddlePitfalls

Testing implementation details

Kent C. Dodds defines implementation details as "things which users of your code will not typically use, see, or even know about". A function's users are its callers. A component has two: the end user who sees and clicks it, and the developer who renders it with props. A test that depends on anything else has two problems, which Dodds names:

  • False negatives: it fails after a refactor although the code still works. People learn to "fix the test" by copying the new internals into it, and stop trusting a red result.
  • False positives: it passes while the code is broken, because it checks internal steps instead of the result.
TypeScript
// ✗ reads internal state
test("stores the item", () => {
  const cart = createCart();
  cart.add({ id: "tea", price: 4 });
  expect(cart._items).toEqual([{ id: "tea", price: 4, quantity: 1 }]);
});

// ✓ uses the public API
test("counts a repeated item in the total", () => {
  const cart = createCart();
  cart.add({ id: "tea", price: 4 });
  cart.add({ id: "tea", price: 4 });
  expect(cart.count()).toBe(2);
  expect(cart.total()).toBe(8);
});

If _items becomes a Map keyed by id, the first test breaks although nothing changed for callers. And it keeps passing if total() is broken, because it never calls it. The second test survives the rewrite and fails exactly when a caller would see a wrong number.

A practical check, from the Vitest guide: if someone rewrites the internals and the output stays the same, should this test break? If it would, it tests an implementation detail.

Signs to look for

  • assertions on private fields, internal state, or how many times something rendered;
  • spying on a helper that the code calls internally, only to check that it was called;
  • mocking modules of the same feature, so the test describes the wiring instead of the result;
  • a test file that changes in the same commit as every refactor.

If a private helper seems to need its own tests, Ham Vocke's advice is that the module probably does too much: move the helper into a module with its own public contract, and test that. For React components the rule reads: interact the way a user does and check what is on the screen, not state or props of children. Testing Library is built around this idea.

Not every outcome is a return value, though. Calling onSave with the form values, sending an analytics event or writing to storage is something callers rely on, and checking it with a test double is testing behaviour. The question is whether the call is part of the contract, or just one way of getting the result.

MiddleConcept

What to test and what to skip

Every test costs time to write, time to run and time to update. Spend them where bugs are likely and expensive.

Worth testing

  • Logic with branches: pricing, discounts, permissions, parsing, formatting, validation rules, reducers, state machines.
  • Boundaries: an empty list, zero, negative numbers, the maximum length, the last day of a month, a missing optional field.
  • Error paths: invalid input, a rejected request, a timeout. Nobody clicks through these by hand.
  • Contracts between parts: the shape a component sends to an API client, the events a widget emits, what a hook returns.
  • Anything that broke before. A bug shows where the code is fragile, and its regression test stops it from coming back.

Usually not worth a test of its own

  • Third-party code. Don't test that React re-renders, that Array.prototype.sort sorts or that a date library parses ISO strings: their own test suites do that. Test your use of them: the order your table promises, the date your function returns for a given input.
  • Trivial code. A getter that returns a field, a component that only passes props through, a constant. Ham Vocke's rule is short: "you don't test trivial code". It still runs in the tests of the code that uses it.
  • What the type checker already proves. If strict TypeScript rejects a call with a missing argument, a test that checks that call only re-tests the compiler.
  • Styling and exact markup. Class names, colours and spacing change often and say little about behaviour. Simulated DOMs such as jsdom do no layout at all (its README says so), so they can't tell whether an element is visible on screen or covered by another. Test the behaviour (a disabled button, an error message), and leave the look to screenshot tests in a real browser.
  • The same rule at every level. If unit tests cover every discount rule, the end-to-end checkout test needs one coupon, not twelve. Vocke's advice is to push tests as far down the pyramid as you can.

A quick filter

Before writing a test, ask two questions. If this behaviour broke, would a user or another developer notice? Would this test tell me sooner, or more precisely, than the tests I already have? If the answer to both is no, the test probably costs more than it returns.

The opposite mistake is skipping the error path because the happy path works. A rejected request with no visible error message is a real bug that only a test, or a user, will find.

MiddleConcept

Code coverage: what it measures and what it doesn't

A coverage tool records which parts of your code ran while the tests were running. Vitest collects it with vitest run --coverage (with the v8 provider by default, or istanbul) and reports four numbers per file:

  • statements and lines: how many executed at least once;
  • functions: how many were called at least once;
  • branches: how many paths through if/else, ? :, &&, ||, ?? and switch were taken.

The report is most useful as a map. Red lines are code that no test ever ran, often an error path nobody thought about.

What coverage can't tell you

Coverage measures what ran, not what was checked:

TypeScript
function shippingCost(total: number, country: string) {
  if (country !== "AZ") return 15;
  return total >= 50 ? 0 : 5;
}

test("shipping", () => {
  shippingCost(10, "AZ");
  shippingCost(60, "AZ");
  shippingCost(60, "DE");
});

This test reaches 100% of lines, functions and branches, and asserts nothing: it passes even if every return value is wrong. Martin Fowler calls the extreme case "AssertionFreeTesting". Even with good assertions, 100% branch coverage doesn't mean every combination of conditions was tried, that the boundary (a total of exactly 50) was checked, or that the code does what the product needs.

Fowler's view is that coverage is "a useful tool for finding untested parts of a codebase" but "of little use as a numeric statement of how good your tests are". Low numbers, "say below half", are a sign of trouble; high numbers don't necessarily mean much. Anything close to 100% would make him suspicious of tests written to satisfy the metric. Kent C. Dodds agrees: returns diminish beyond about 70% (a number he admits is made up), and mandating 100% for an application is "a really bad idea".

Coverage in CI

coverage.thresholds in the Vitest config sets minimum percentages for lines, functions, branches and statements, and a run below them exits with an error, which fails the CI job. Used as a floor, a threshold stops coverage from quietly dropping when untested code is added. Used as a target, it invites tests like the one above. Fowler quotes Brian Marick on the difference: "I expect a high level of coverage. Sometimes managers require one. There's a subtle difference."

In review, look at the changed lines: is the new branch covered, and is there an assertion that would fail if that branch returned the wrong value?

SeniorConcept

Tests in CI and in code review

Tests protect a codebase only if they run on every change and nothing merges while they fail. A pipeline for a pull request runs the cheapest checks first, so a typo fails in seconds rather than after a long browser run:

Shell
npx tsc --noEmit
npx eslint .
npx vitest run --coverage
npx playwright test

On a developer machine, vitest starts in watch mode, but in CI (when process.env.CI is set) or in a non-interactive terminal it does a single run. Two CI defaults matter for review. Vitest doesn't write snapshots in CI: a missing, changed or obsolete snapshot fails the run instead of being recorded, so a snapshot changes only when someone updates it locally and commits the diff. And allowOnly is off in CI, so a forgotten test.only fails the suite instead of silently skipping every other test.

Keep the suite fast and trustworthy

  • A time budget. Fowler cites Kent Beck's rule of thumb that the commit suite should take no more than ten minutes. A slower suite is run less often locally, and its feedback arrives after the developer has moved on.
  • Determinism. A test that sometimes fails without a code change is worse than no test: people rerun the pipeline until it is green, and the next real failure gets the same treatment. Fowler calls non-deterministic tests "useless" and "a virulent infection", and advises quarantining them and fixing them quickly rather than hiding them behind automatic retries.
  • One command. Developers should be able to run locally exactly what CI runs, with the same configuration.

Reviewing tests in a pull request

Read the tests before the code: they say what the author meant the change to do.

  • Is there a test for the new behaviour, at the lowest level that can show it?
  • Would it fail without the change? If that is not obvious, check out the branch, revert the fix and run the test.
  • Do the assertions check results (return values, text on screen, requests sent) or internals?
  • Did existing expected values change? A refactor that needs new expected values is not a refactor; ask which behaviour changed and whether that was intended.
  • Is every updated snapshot explained by the change?

Tests as a design signal

If a component needs a dozen mocks before it can be tested, the problem is the design, not the test: it does too much or reaches into too many modules directly. A test that is painful to write is often the first warning that the code will be painful to change.

SeniorExample

A bug report: regression test first, at the right level

A bug report is the best moment to add a test: you know the code is fragile there, and you have a concrete failing case. Martin Fowler's advice for a bug exposed by a high-level test is to replicate it with a unit test before fixing it, and Ham Vocke's version is: if a higher-level test spots an error and no lower-level test fails, write a lower-level test.

The report: "Free shipping is not applied when the cart total is exactly 50."

  1. Reproduce it at the lowest level that can show it. The rule lives in shippingCost, a pure function, so a unit test can:
TypeScript
test("ships free at exactly the threshold", () => {
  expect(shippingCost(50, "AZ")).toBe(0);
});
  1. Watch it fail for the reported reason: it receives 5 instead of 0. If it passes, the bug is somewhere else, and the test has just saved you from a wrong fix.
  2. Fix the code (total > 50 becomes total >= 50), watch the test pass, then run the whole suite: some other code may have relied on the old rule.
  3. Keep the test. It documents the decision that exactly 50 ships free, and it fails if anyone reintroduces the bug.

Choosing the level

The lowest level that reproduces the bug is usually right, but not every bug lives inside one unit:

The bug is inWriteExample
a rule inside one function or modulea unit testrounding, a date boundary, a reducer case
the contract between partsan integration testthe form sends qty, the API client reads quantity
something only the running app showsan end-to-end testa route that 404s after a deploy, a cookie that is never sent

If a user or an end-to-end test found the bug and a lower-level test can reproduce it, prefer the lower-level test: it is faster, points at the cause and doesn't flake. Keep an end-to-end test for the bugs nothing lower can show.

When a test is not worth it

A regression test is cheap insurance when logic can break again. It adds little when the fix was in data rather than code (a bad record in the database), when the bug was a typo in a text, or when the only test that reproduces it would be so slow or unreliable that the team would soon skip it. Then say so in the pull request, so the reviewer knows the gap is deliberate.

SeniorInterview tips

Interview tips

A 30-second answer. "Tests give me confidence to change code and describe what it must do. I choose the level by what can break: unit tests for logic, integration tests for how parts work together, which in a React app means rendering components with their real children and faking only the network, and a few end-to-end tests in a real browser for the journeys that must never break. Higher levels give more confidence per test but are slower, flakier and harder to debug. I test behaviour through the public API, not implementation details, so refactors don't break tests. Coverage shows me what is untested; it doesn't tell me the tests are good."

Questions you are likely to get

  • Pyramid or trophy? Name both and their authors (Mike Cohn, described by Martin Fowler; Kent C. Dodds), explain that much of the disagreement is about what a "unit" is, and say what you would choose for this kind of app and why.
  • What is an implementation detail? Something callers can't see or use. Give the false-negative and false-positive argument with an example, such as a test that reads a component's state.
  • Is 100% coverage a good goal? No: coverage shows what ran, not what was checked. Use it to find untested code and as a floor in CI.
  • How do you handle a bug report? Reproduce it with a failing test at the lowest level that shows it, fix the code, keep the test.
  • What would you not test? Third-party code, trivial code, what the type checker proves, styling details.
  • Why are end-to-end tests flaky, and what do you do about it? Many moving parts: network, data, timing, the browser. Keep them few, make them deterministic, quarantine and fix flaky ones instead of retrying.

Mistakes that cost points

  • Defining levels by tool ("Vitest is unit, Playwright is E2E"). A Vitest test that renders a whole form with its real API client and a fake network is an integration test.
  • Treating the pyramid or the trophy as a rule rather than a model of costs.
  • Calling a test that only checks that a mock was called "testing behaviour" when that call is not part of the contract.
  • Offering "we have 90% coverage" as proof that the code is well tested.

Senior signal

Talk about the suite as something with running costs: how long CI takes, which tests flake and who fixes them, which tests break on every refactor, which bugs reached production and which level should have caught them. Place tests by risk: payments and sign-in get end-to-end coverage, a date helper gets a table of unit tests, a static marketing page gets almost none. Treat a hard-to-test module as a design problem, not as a reason to mock more.

JuniorReview checklist

What to check when reviewing tests

Use this list when you review tests you did not write: in a teammate's pull request, in a library's example or in an AI assistant's suggestion. In a green CI run a weak test looks the same as a strong one; skip this review, and you get bugs that are "covered" and refactors that break dozens of tests.

  • Would the test fail if the behaviour broke? Break the code on purpose, or revert the fix, and run it. A test that stays green, has no expect, or computes the expected value with the same logic as the code checks nothing; Vitest's expect.requireAssertions option makes tests without assertions fail.
  • Does it check what a caller can observe? Return values, thrown errors, text on the screen and requests sent survive refactors. Assertions on private fields, internal state or calls to internal helpers break on every rewrite and still miss real bugs.
  • Is it at the lowest level that can show the behaviour? Rules belong in fast unit tests, wiring in integration tests. An end-to-end test for one validation rule is slow and flaky, and a unit test with every neighbour mocked can't catch a field name that two modules disagree on.
  • Does each name state one behaviour? Read describe and test names as a sentence: "applyCoupon > rejects an expired coupon" says what broke; "works", or a name joined with "and", hides several cases.
  • Are edge cases and error paths tested, not only the happy path? Look for empty input, zero, boundaries such as "exactly 50" and rejected requests. The coverage report shows branches that no test ran.
  • Does the test depend on anything outside itself? State left by other tests, the real clock, random values or the network make it pass or fail by chance. Run the file alone and in random order (vitest run cart.test.ts --sequence.shuffle) to check.
  • Is every changed expected value or snapshot intended? Ask which behaviour changed and why. An updated snapshot that nobody read is an accepted bug.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    7 questions