A test suite is only worth running if it fails for the right reason. Most React teams accumulate hundreds of tests that assert on internal state, then discover during a refactor that every one of them broke while the actual product behavior never changed. The fix is not more coverage, it is a different question: stop asking whether the component's internals look the way you expected, and start asking whether the screen in front of the user does what a person would need it to do.
âšī¸The priority order
Query by accessible role first, then by label, then by visible text, and only then by test id. Every step down that list is a step toward a test that breaks when you rename a variable, which is exactly the kind of breakage that teaches you nothing.
Test the behavior a user can see
A user does not know that a piece of state called isSubmitting exists. They know that after clicking a button, the button says Submitting and stops responding to clicks. Asserting on the visible outcome means the test documents intent at the same time as it verifies it, so a colleague reading the test three months later understands the feature without opening the component.
React Testing Library is built around this idea. Its queries mirror how assistive technology exposes the page: a button is found by its accessible name, an input by its associated label, a heading by its level and text. When a test can only be written by reaching into a ref or reading a data attribute you added solely for testing, that is usually a signal the component is doing too much or the UI lacks a real accessible name.
A first test that earns trust
The example below exercises a signup form the way a person would: type into labelled fields, submit, wait for a server response, and confirm the success message appears. Nothing in the assertions refers to component state.
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { server } from '../test/server';
import { http, HttpResponse } from 'msw';
import SignupForm from './SignupForm';
describe('SignupForm', () => {
it('creates an account and shows confirmation', async () => {
server.use(
http.post('/api/signup', () =>
HttpResponse.json({ ok: true, userId: 'u_42' })
)
);
render(<SignupForm />);
const user = userEvent.setup();
await user.type(screen.getByLabelText(/email address/i), 'ada@example.com');
await user.type(screen.getByLabelText(/^password/i), 'correct horse battery');
await user.click(screen.getByRole('button', { name: /create account/i }));
expect(
await screen.findByRole('status')
).toHaveTextContent(/check your inbox/i);
expect(screen.getByLabelText(/email address/i)).toBeDisabled();
});
it('blocks submission when the password is too short', async () => {
render(<SignupForm />);
const user = userEvent.setup();
await user.type(screen.getByLabelText(/email address/i), 'ada@example.com');
await user.type(screen.getByLabelText(/^password/i), 'short');
await user.click(screen.getByRole('button', { name: /create account/i }));
expect(await screen.findByText(/at least 12 characters/i)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /create account/i })).toBeEnabled();
});
});
Note what is absent: no assertion on a state variable, no query for an internal class name, no direct call of the submit handler. If you later replace the form with a server component plus a form action, the same test still describes the desired outcome, and it will keep failing until the new implementation satisfies it.
Async work without flaky waits
The enemy of a fast suite is arbitrary waiting. Sleeps of two hundred milliseconds hide races and slow every run, while a bare waitFor with no timeout turns a genuine bug into a two-second stall before a confusing failure. Prefer queries that poll: findByRole and findByText retry until the assertion passes or the timeout expires, and they fail with a helpful dump of the accessible roles that were actually present.
Timers deserve their own discipline. Any component that debounces, auto-saves, or shows a toast after a delay is a candidate for fake timers, but mixing them with real network calls is the classic source of hangs, because the fake clock freezes while the real request never resolves.
import { render, screen, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import SearchBox from './SearchBox';
jest.useFakeTimers();
it('waits 300ms after the last keystroke before searching', async () => {
const onSearch = jest.fn();
render(<SearchBox onSearch={onSearch} />);
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
await user.type(screen.getByRole('searchbox'), 'react');
expect(onSearch).not.toHaveBeenCalled();
await act(() => jest.advanceTimersByTime(300));
expect(onSearch).toHaveBeenCalledTimes(1);
expect(onSearch).toHaveBeenCalledWith('react');
});
Two details make this reliable. userEvent is created with advanceTimers so its own internal delays use the fake clock, and the time jump is wrapped in act so React flushes the pending state update before the assertion runs. Forgetting either one produces a test that passes locally and fails on the build agent.
Where each layer of testing pays for itself
Testing is economics before it is technique. Every layer costs minutes of runtime and hours of maintenance, so the question is which class of bug each layer catches that the layer below it cannot.
| Layer | Typical tool | Bugs it catches | Runtime cost | Add it when |
|---|---|---|---|---|
| Unit | Vitest or Jest | Pure logic errors, reducers, formatters | Milliseconds | A function has branches worth enumerating |
| Component | Testing Library | Wrong visible outcome, broken accessibility names | Seconds | The component owns non-trivial interaction |
| Integration | Testing Library plus MSW | Contract drift between components and API | Seconds to a minute | Several components share one flow |
| End to end | Playwright | Routing, auth, deploy and network failures | Minutes | A flow is the reason the product exists |
| Visual | Storybook plus Chromatic | Layout regressions, clipped text, contrast | Minutes | Styling changes ship without review |
A healthy project has a pyramid that is wider at the bottom but never empty at the top: a handful of end to end tests covering signup, checkout and the primary search path, a layer of integration tests over the flows that combine several components, and a broad base of fast tests for logic.
The mocking boundary
Mock at the edge of the system, not inside it. Mocking the API is reasonable, because network behavior is nondeterministic and the point of a component test is the component. Mocking a sibling component, a custom hook, or a utility function your own code owns is usually a mistake: you replace real code with a hand-written approximation, and the test now verifies your approximation instead of your product.
The Mock Service Worker approach takes this further by intercepting requests at the network layer rather than inside the module graph, so the component under test imports the same code in tests as it does in production. Handlers live in one place and can be overridden per test, which keeps the arrange step short and the failures legible.
// src/test/server.js
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
export const handlers = [
http.get('/api/profile', () =>
HttpResponse.json({ name: 'Ada Lovelace', plan: 'pro' })
),
http.post('/api/login', ({ request }) => {
const body = request.json();
if (!body.password) {
return HttpResponse.json({ error: 'Password required' }, { status: 400 });
}
return HttpResponse.json({ token: 'test-token' });
}),
];
export const server = setupServer(...handlers);
Keeping the suite honest in continuous integration
A suite that takes eleven minutes gets skipped, and a skipped suite is worse than no suite because it looks like protection. Split the run: unit and component tests on every pull request with coverage thresholds, end to end tests on merge and on the main branch. Fail the build on a test that fails twice in a row rather than on the first flake, so genuine regressions are still loud while environment noise does not train people to hit retry.
Coverage deserves a warning rather than a celebration. A number tells you which lines executed, not whether anyone asserted anything meaningful about them. Read the diff of coverage on a pull request and ask which new branches have no test, rather than chasing a global percentage that mostly measures how much logging you wrote.
Common Mistakes
Asserting on state, internal props or class names that a refactor can rename freely
Fix: Query by accessible role, label or visible text so the test documents what the user experiences.
Waiting a fixed amount of time for async work to finish
Fix: Use findBy queries or waitFor with a specific assertion, and reserve fake timers for code you control.
Mocking your own modules so the test passes without real logic running
Fix: Mock the network boundary instead, and let the component import the production implementation.
Treating coverage percentage as the quality goal
Fix: Review uncovered branches in the diff and ask which user-visible behavior could break without a test noticing.
Best Practices
- Give every test one behavior in the name so a failure explains itself before anyone opens a stack trace
- Share server handlers as defaults and override only the field the scenario needs
- Run the fast layers on every pull request and reserve end to end tests for flows that justify their minutes
- Delete tests that assert on implementation details rather than repairing them, because a misleading test costs more than an absent one
Key Takeaways
- Test what the user can perceive, because visible outcomes survive refactors while internal assertions do not
- findBy and waitFor retry against a real assertion; fixed sleeps only hide races and slow the suite
- Mock at the network boundary with something like Mock Service Worker so components import production code in tests
- Each layer of the testing pyramid catches a class of bug the layer below cannot, so choose by economics rather than by fashion
- Fake timers and real network calls do not mix: configure userEvent to advance the fake clock or the test will hang