What you'll learn: By the end of this lesson you will be able to define a unit for a front end, tell solitary from sociable tests, name the kinds of test double and pick one on purpose, test a component through its public surface instead of its internals, explain why a test that reads internals fails after a harmless refactor and passes after a real bug, and use role-based queries and simulated user input the way Testing Library recommends.
Think of a vending machine. You can test it from the outside: put in a coin, press B4, check what drops and what the display says. Or you can open the back and check that a particular spring moved. The second test is precise, but replace that spring with a motor and it fails although the machine still sells crisps; and a jammed coin slot would never show up in it. A good component test is the first kind.
The running example is the quantity stepper on a ShopStream product page: a "minus", a number, a "plus", and a typed-in field, with a minimum of 1 and a maximum that the stock allows.
The core idea
- A test should know what a user or a parent component knows. For a component that is its props, the events a user produces, what is rendered, and the callbacks it calls. Everything else is an implementation detail.
- Replace a collaborator only for a reason. Slow, nondeterministic or external things (the network, timers) are replaced; ordinary children and helpers usually run for real.
- A test is good when it fails for a bug and stays green for a refactor. A test that does the reverse costs trust twice.
What a unit is
The word is not fixed. Martin Fowler's bliki entry on unit tests says the term is very ill-defined, that an object-oriented design tends to treat a class as the unit while a procedural or functional one may treat a single function as the unit, and that it is "a situational thing": the team decides what makes sense. Kent C. Dodds defines a unit as a single function, class or object that contains logic. For a front end a workable choice is: a unit is one function or hook with logic (parsing, formatting, a reducer, a price rule); a component test renders or drives one component with its real children and logic and replaces only the outside world.
Fowler also describes two styles. Solitary tests replace every collaborator with a test double; sociable tests use the real collaborators. He credits the terms to Jay Fields, notes that "mockists" prefer solitary tests and "classicists" prefer sociable ones, and says he still uses a double where a collaboration is awkward. Component tests in the Testing Library style are sociable: the stepper runs with its real parsing and clamping.
Test doubles, named
Fowler's article "Mocks Aren't Stubs" lists Gerard Meszaros' vocabulary, which is worth using precisely:
| Double | What it is | Typical front-end use |
|---|---|---|
| Dummy | Passed around, never used | A required prop the test does not care about |
| Stub | Canned answers to calls | A service that returns a fixed order id |
| Spy | A stub that also records how it was called | An onChange callback whose calls you inspect |
| Fake | A working shortcut implementation | An in-memory storage or fake API |
| Mock | Pre-programmed with expectations it verifies itself | A strict collaborator contract |
He also separates state verification (check the result by looking at the state of the unit and its collaborators) from behaviour verification (check that the right calls were made on collaborators). Only mocks require behaviour verification. A rule of thumb that follows: verify state or rendered output where you can, and verify calls only for effects that leave your code, such as "the parent was told once".
Figure 1. What a component test may touch
How to read this: inputs enter on the left and observable results leave on the right. The accent box in the middle is where the implementation lives (variables, reducers, helper functions). A test that reads inside that box is coupled to it.
Testing a component the way it is used
The Testing Library guiding principle is that the more your tests resemble the way your software is used, the more confidence they can give you. Its principles ask for utilities that deal with DOM nodes rather than component instances, and that encourage tests that use components the way they are intended to be used. Kent C. Dodds' post on implementation details defines them as "things which users of your code will not typically use, see, or even know about", and describes two failure modes of testing them: a false negative when you refactor (the test fails although the app still works) and a false positive when you break the code (no test fails although it should).
The practical rules that follow:
- Query by what a user perceives. The Testing Library query documentation lists
getByRoleas the top preference "for just about everything", then label text (good for form fields), then text, with test ids last and only when you cannot match by role or text. A role query also checks that the element is exposed to assistive technology the way you meant. - Choose the right variant.
getByreturns the node and throws if there is no match or more than one;queryByreturns null when there is no match, which makes it the tool for asserting that something is absent;findByreturns a promise that resolves when the element appears, retrying until a default timeout of 1000 ms. - Simulate people, not events. The
user-eventdocumentation says it lets you describe a user interaction instead of a concrete event, dispatching the events that would happen in a browser, and recommends callinguserEvent.setup()before the component is rendered.fireEvent, by contrast, dispatches one DOM event. - Replace time, not logic. Vitest's fake timers mock
setTimeoutandsetIntervalso a test of a debounce does not wait;vi.advanceTimersByTime(ms)moves fake time forward by a set amount. The same page notes thatvi.useFakeTimersalso changes theDatetime, and the mocking guide says to clear or restore mocks between tests.
A caveat worth keeping in mind: jsdom is not a browser. A test under jsdom can check roles, text and event handling; it cannot show layout, scrolling or how a screen reader announces something.
Illustration 1: the minimal example
A unit test of a pure function is the cheapest test there is. Vitest's test.each runs the same test with different variables, and the format specifiers fill the title. From the lab below, the function that turns what the user typed into a quantity:
it.each([
["2", 2],
[" 2 ", 2],
["99", 3],
["0", 1],
["", null],
["abc", null],
["-1", null],
["2.5", null],
["1e1", null],
])("parseQuantity(%j) is %j", (raw, expected) => {
expect(parseQuantity(raw, 1, 3)).toBe(expected);
});
Each row is a case, the title names it, and a new case is one line. The table shows the edges (empty, negative, decimal, exponent notation) that a person tends to forget.
Illustration 2: the realistic example
The stepper sits next to a product in a grid. The parent passes min 1 and a max from stock, and an onChange callback that updates the cart. A behaviour check, written against the public surface only, with a spy for the callback:
const s = spy();
const stepper = make({ ...bounds, initial: 1, onChange: s.onChange });
stepper.press("increase");
assert.equal(stepper.view().value, 2);
assert.deepEqual(s.calls, [2]);
It states what a parent cares about: the value shown is 2 and the parent was told once, with 2. It says nothing about how the stepper keeps its value. Replace the stepper's internals and this check is unaffected.
The lab (below) is DOM-free. In a React project the same intent reads like the following excerpt from the existing feed lab, examples/frontend/labs/pagination-infinite-scroll, which renders a real component with Testing Library under jsdom:
expect(screen.getByRole("alert")).toHaveTextContent("Network down");
expect(articles()).toHaveLength(10);
await user.click(screen.getByRole("button", { name: "Try again" }));
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
It finds things by role and accessible name, clicks through user-event, and uses queryByRole to assert that the alert is gone. The lab's tests (33 of 33 passed, Vitest 5.1.0 on Node 26.13.1) observed behaviour in jsdom only: no layout, no screen reader.
Build it
The lab examples/frontend/labs/refactor-safe-tests writes the stepper twice: version A keeps one variable, version B is a refactor into a state object and a reducer. Both have the same public behaviour. Two styles of check run against both: 6 behaviour checks (public surface, with a spy) and 2 coupled checks that read an internal field. They also run against two seeded bugs of version A: the plus button allowed one step past the maximum, and onChange fired when the typed value equalled the current value.
cd examples/frontend/labs/refactor-safe-tests
../../node_modules/.bin/vitest run
node src/demo.ts
The 20 tests passed (Vitest 5.1.0, Node 26.13.1). The stepper's "view" is a plain object, not a rendered component, so the lab shows the idea of behaviour versus internals, doubles and table-driven tests; it does not show how Testing Library renders or queries a real component.
Expected output, captured from a real run (the whole demo):
behaviour: 6 checks
coupled: 2 checks
implementation behaviour coupled
A 6 pass, 0 fail 2 pass, 0 fail
B (refactor of A) 6 pass, 0 fail 0 pass, 2 fail
A + offByOneMax 5 pass, 1 fail 2 pass, 0 fail
A + notifyUnchanged 5 pass, 1 fail 2 pass, 0 fail
what the coupled style says about the refactor (B behaves exactly like A):
FAIL after increase the internal variable `debug.value` is 2
FAIL typing 3 leaves `debug.value` at 3
what the behaviour style says about the two seeded bugs:
A + offByOneMax: FAIL increase is disabled at the maximum and the value never passes it
A + notifyUnchanged: FAIL typing the value it already has does not tell the parent
Version B behaves exactly like A (the test suite asserts the same view for the same sequence of actions), yet both coupled checks fail on it: they read debug.value, which B does not have. That is Dodds' false negative. The two seeded bugs are caught by exactly one behaviour check each and by no coupled check, because the coupled checks never push past the maximum and never type the current value. That is his false positive.
Illustration 3: a failure, from the lab
Read the matrix as a refactoring story. A team rewrites the stepper to use a reducer and nothing a user can see changes, yet two tests go red and someone spends an afternoon "fixing" tests whose only fault was reading a variable that moved. Later a real bug (the quantity can exceed stock) arrives and the coupled tests stay green. The behaviour checks do the opposite on both counts. Internals tests are not always wrong (a pure function's contract is its internals, and a table of cases is exactly right); a component test should be pinned to what the component promises.
Figure 2. Which double, and when
local and deterministic?"} A -->|"yes"| R["Use the real one
(sociable test)"] A -->|"no"| B{"What does the test need?"} B -->|"just an answer"| S["Stub"] B -->|"also: was it called?"| P["Spy
assert on outgoing effects only"] B -->|"working behaviour"| F["Fake
(in-memory storage, fake API)"] B -->|"strict call script"| M["Mock
use sparingly"]
How to read this: the default is the real collaborator. Each step away from it buys determinism and costs fidelity, so go only as far as the test needs.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Solitary tests (doubles everywhere) | Failures point at one unit | Tests mirror the code; refactors break them |
| Sociable tests (real collaborators) | Survive refactors; resemble use | A failure can come from a collaborator |
| Role and name queries | Tied to what users perceive; double as an accessibility check | Needs correct roles and labels in the markup |
| Test ids | Stable when text changes | Invisible to users; not a check of accessibility |
| Spies on callbacks | Verify effects that leave your code | Easy to over-specify call order and counts |
| Fake timers | Fast, deterministic time | Must be restored; also moves the Date |
| jsdom | Fast, runs in Node | Not a browser: no layout, no real screen reader |
In practice: the cart quantity stepper
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every detail in it is an illustrative assumption.
The situation
The cart page has a quantity stepper per line. The component was written with several pieces of local state, and the tests were written with it: they render the component and then check its state variables and mock its own helper functions. A planned refactor to a reducer would invalidate most of them. Meanwhile a customer reports that they could order more than the stock allows.
Starting architecture
Figure 3. Tests glued to the inside
How to read this: the warning box talks to the component's internals instead of its props and callbacks, so any internal change breaks it, and nothing checks the parent contract.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Keep the tests, update them after the refactor | No up-front work | Rewrite per refactor | The stock bug stays unchecked |
| Rewrite as behaviour tests through props and callbacks first | Refactor-safe; the stock rule gets a test | A day of rewriting | Under-specified at first |
| Replace with end-to-end tests | Resembles real use | Slow and broad | A failure names a symptom |
The decision
| Field | Decision record |
|---|---|
| Context | Tests read internals; a refactor is planned; the maximum is not checked. |
| Decision | Rewrite the checks against props, user input, rendered output and a spy on onChange, run them on the current code, then refactor. Put parsing and clamping in pure functions with table-driven tests. Add a check that the plus control is disabled at the stock limit. |
| Consequences, good | The refactor changes no tests; the stock rule is covered. |
| Consequences, bad | A few tests duplicate rules that the pure functions also cover. |
| Revisit when | The parent contract (props, callbacks) changes. |
Rollout and verification
- Write the behaviour checks first and see them pass on the old code.
- Seed a bug on purpose (plus allowed at the maximum) and confirm a check fails; remove it.
- Refactor and confirm the same checks stay green with no edits.
The 2 a.m. failure
A stock update lowers the maximum below the quantity already in the cart. The stepper shows 5 with a maximum of 3; plus is disabled but the value is out of range, and checkout is rejected. The old tests never covered a changing max.
First three checks: (1) reproduce with props max 3 and initial 5 in a test; (2) read what the stepper should do (clamp the value and tell the parent); (3) check whether any behaviour check covers a prop that changes after mount. Mitigation: clamp on prop change and notify the parent. Follow-up: a behaviour check for a changing max.
Figure 4. A refactor under two styles of test
How to read this: the same two changes, a harmless refactor and a real bug, produce opposite signals from the two styles. A suite is only as useful as it is right about both.
Architect's notes
- Name tests after behaviour ("increase is disabled at the maximum"), not after code ("calls setCount").
- Put logic in pure functions and test them with tables; keep the component thin.
- Default to real collaborators; add a double for the network and for time.
- Seed a bug on purpose once in a while to confirm the tests can fail.
Common mistakes
- Reading state, refs or private helpers from a test.
- Snapshotting a whole rendered tree and approving changes without reading them.
- Mocking your own modules so heavily that the test checks the mocks.
- Querying by test id first, though a role or label would work.
- Not restoring fake timers or mocks between tests.
- Asserting call counts and order that the parent does not depend on.
Key takeaways
- A unit is whatever the team defines; for a front end, a function or hook with logic, or one component with its real children.
- Prefer sociable tests; replace the network and time, not your own code.
- Use the double you need: stub for answers, spy for recorded calls, fake for working behaviour, mock sparingly.
- Test through props, user input, rendered output and callbacks.
- Query by role and name first; use test ids last.
- A good test fails for a bug and survives a refactor.
Practice exercises
Exercise 1: Starter (30 min). Add three rows to the parseQuantity table (for example "00", "+2" and "٣") and predict each result before running it. Explain any surprise.
Exercise 2: Intermediate (2 hours). Write a third implementation of the stepper (a class) and run both styles of check against it before reading the output. Which style needs a change, and why?
Exercise 3: Advanced (half day). Rewrite one component test of your own that reads state or mocks a helper against props, input and output, seed a bug, and show that it fails.
Related reading
In this course:
- The Testing Pyramid and Trophy for Front Ends: where unit and component tests sit among the layers.
- Component Composition and API Design: the public surface a component test should be pinned to.
- React Purity, Strict Mode and Refs: why a pure render is easy to test.
- Error, Loading and Empty States: states worth a component test each.
Later in this module: integration testing with network mocking, end-to-end testing and flakiness.
Official documentation
- Martin Fowler: Unit Test: what a unit is, solitary and sociable tests.
- Martin Fowler: Mocks Aren't Stubs: the vocabulary of test doubles.
- Kent C. Dodds: Testing Implementation Details: false negatives and false positives.
- Testing Library: About Queries: query priority and the getBy, queryBy and findBy variants.
- Testing Library: user-event introduction: describing interactions rather than events.
- Vitest: test.each and Timers: table-driven tests and fake timers.