Lesson 27 of 37Real projects
Testing React
Write component tests with Vitest and Testing Library, mock the network with MSW, and cover key flows with Playwright.
Tests are how a team changes code on a Friday afternoon without fear. In job interviews and take-home reviews, a few well-chosen tests often count for more than an extra feature, because they show you think about what can break. This lesson covers the modern React testing stack: Vitest, React Testing Library, MSW, and Playwright.
The testing pyramid for frontends
Different tests trade speed for confidence.
The base is free: TypeScript and ESLint catch a whole class of bugs on every save.
Vitest and React Testing Library
Vitest is a test runner built on Vite, so it shares your config, understands TypeScript and JSX, and is fast. React Testing Library (RTL) renders components into a simulated browser DOM (jsdom) and gives you queries that find elements the way users do: by role, label, and text.
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-domimport { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
setupFiles: "./src/test/setup.ts",
},
});import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";
afterEach(() => cleanup());The first import adds matchers such as toBeInTheDocument. The cleanup line removes each test's rendered output before the next test. Testing Library only does that by itself when Vitest's globals option is on, so without it a second render in the same file finds two copies of everything and fails with "Found multiple elements".
Here is a component and its test. The component runs in the preview; the test file runs with npx vitest.
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, expect, it } from "vitest";
import Counter from "./Counter";
describe("Counter", () => {
it("increments and resets", async () => {
const user = userEvent.setup();
render(<Counter />);
expect(screen.getByText("Count: 0")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Reset" })).toBeDisabled();
await user.click(screen.getByRole("button", { name: "Increment" }));
await user.click(screen.getByRole("button", { name: "Increment" }));
expect(screen.getByText("Count: 2")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Reset" }));
expect(screen.getByText("Count: 0")).toBeInTheDocument();
});
});The pieces:
render(<Counter />)mounts the component into jsdom.screen.getByRole("button", { name: "Increment" })finds the element by its accessible role and name, the same information a screen reader uses.userEventsimulates real interactions:user.click,user.type(input, "Ada"),user.keyboard("{Enter}"). It fires the full sequence of events (pointer down, focus, click), so it catches more bugs than the lower-levelfireEvent.- Matchers like
toBeInTheDocument()andtoBeDisabled()come from@testing-library/jest-dom.
Match the query to when you use it.
Test behaviour, not implementation
The guiding principle of Testing Library: the more your tests resemble the way your software is used, the more confidence they can give you. A test should break when the user-visible behaviour breaks, not when you rename a state variable or swap useState for useReducer.
// Reaches into internals: breaks on any refactor, misses real bugs
expect(container.querySelector(".counter__value")!.textContent).toBe("2");
expect(component.state.count).toBe(2);
expect(setCountSpy).toHaveBeenCalledWith(2);// Checks what a user sees and does
await user.click(screen.getByRole("button", { name: "Increment" }));
expect(screen.getByText("Count: 1")).toBeInTheDocument();Query priority, best first: getByRole → getByLabelText (form fields) → getByText → getByTestId (last resort). A happy side effect: if you cannot find your button by role and name, a screen reader user cannot either. Tests push you toward accessible markup.
useState calls to one useReducer. The UI is identical. Which test should still pass?Here is a tiny version of what RTL's queries do under the hood, in plain TypeScript. The "DOM" is a list of objects with a role and an accessible name.
Press Run (⌘ Enter) to see what happens.Mocking the network with MSW
Components that fetch should not hit a real server in tests: it is slow, flaky, and changes underneath you. Mock Service Worker (MSW) intercepts requests at the network level and answers with fixtures. Your component code stays unchanged: it still calls fetch, it just gets a fake response.
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
export const server = setupServer(
http.get("/api/todos", () =>
HttpResponse.json([{ id: 1, title: "Write tests" }])
)
);
// In setup.ts: beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close());it("shows todos from the API", async () => {
render(<TodoList />);
expect(screen.getByText("Loading...")).toBeInTheDocument();
expect(await screen.findByRole("listitem")).toHaveTextContent("Write tests");
});
it("shows an error when the API fails", async () => {
server.use(http.get("/api/todos", () => new HttpResponse(null, { status: 500 })));
render(<TodoList />);
expect(await screen.findByRole("alert")).toHaveTextContent("Could not load todos");
});The test mounts the component in jsdom. It shows Loading....
The same handlers can run in the browser during development, so frontend work does not wait for the backend.
End-to-end with Playwright
Playwright starts your real app and drives real browsers. Use it for a handful of journeys where a break would hurt: signing up, paying, publishing. Its locators mirror Testing Library's (getByRole, getByLabel), and its assertions wait automatically.
import { expect, test } from "@playwright/test";
test("a visitor can sign up", async ({ page }) => {
await page.goto("/");
await page.getByLabel("Email").fill("ada@example.com");
await page.getByRole("button", { name: "Sign up" }).click();
await expect(page.getByText("Thanks! Check ada@example.com")).toBeVisible();
});npm init playwright@latest # installs browsers and a confignpx playwright test # runs headless in Chromium, Firefox, WebKitnpx playwright test --ui # watch mode with a time-travel debuggerPut the steps of a typical component test in order.
- Tap the steps below in the right order.
Testing async UI without flaky tests
A flaky test passes on your laptop and fails one run in ten on CI. Flaky tests are worse than no tests: the team learns to press "re-run" instead of reading failures, and real bugs slip through. Most React flakiness comes from asserting at the wrong moment, before the UI has caught up with an async change.
Testing Library gives you three tools for waiting, and each has a job:
findBy...waits for an element to appear. It isgetByplus retries, and it is what you want most of the time:await screen.findByRole("alert").waitFor(() => assertion)retries an assertion until it passes or times out (1 second by default). Use it when the thing you wait for is not an element appearing: a mock being called, a value changing, a button becoming enabled.waitForElementToBeRemoved(() => screen.queryByText("Loading..."))waits for something to disappear, such as a spinner.
Under the hood, all of them poll. Here is a tiny waitFor in plain TypeScript, so you can see why the rules below exist.
Press Run (⌘ Enter) to see what happens.Because the callback runs many times, these rules follow:
- Put assertions inside
waitFor, never actions.waitFor(() => user.click(button))clicks again on every retry. - One assertion per
waitFor. If you wait for five things, a failure tells you less and the retries take longer. - Do not use
waitForwithgetByto wait for an element. UsefindBy, which says what you mean. - Never sleep.
await new Promise((r) => setTimeout(r, 500))is too slow on a fast machine and too short on a busy CI runner. Wait for a condition instead.
The other big source of flakiness is time. A debounced search, a toast that hides after 5 seconds, or a retry with backoff makes a test depend on the clock. Use fake timers, and tell userEvent about them, or it will wait for real time between keystrokes and hang:
beforeEach(() => vi.useFakeTimers({ shouldAdvanceTime: true }));
afterEach(() => vi.useRealTimers());
it("searches after the user stops typing", async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<SearchBox />);
await user.type(screen.getByRole("searchbox"), "react");
await act(() => vi.advanceTimersByTimeAsync(300)); // the debounce delay
expect(await screen.findByRole("listitem")).toHaveTextContent(/react/i);
});The rest of the usual suspects: MSW handlers overridden with server.use in one test and not reset in afterEach, so they leak into the next; tests that depend on running order; Date.now() or random ids in the output; and animations that are still running when you assert. If you see the warning "An update to X inside a test was not wrapped in act(...)", React is telling you that state changed after your test thought it was finished. The fix is almost never to add act by hand; it is to await the thing that causes the update, usually with a findBy.
Testing hooks and context providers
Custom Hooks showed renderHook for a hook on its own. In a real app the harder part is that components need providers to render at all: a router, a query client, a theme, an auth context. Wrapping every test by hand is noisy, and forgetting one gives confusing errors.
The standard fix is a custom render in a shared test-utils file, which wraps every component in the same providers your app uses and re-exports everything else:
import { render, type RenderOptions } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { ReactElement, ReactNode } from "react";
import { AuthProvider } from "@/features/auth/AuthProvider";
import type { User } from "@/features/auth/types";
export function renderWithProviders(ui: ReactElement, { user = null, ...options }: RenderOptions & { user?: User | null } = {}) {
// A fresh client per test, so cached data never leaks between tests.
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
function Wrapper({ children }: { children: ReactNode }) {
return (
<QueryClientProvider client={queryClient}>
<AuthProvider initialUser={user}>{children}</AuthProvider>
</QueryClientProvider>
);
}
return { queryClient, ...render(ui, { wrapper: Wrapper, ...options }) };
}
export * from "@testing-library/react";Three details carry a lot of weight. A new QueryClient per test stops one test's cached data making the next pass by accident. retry: false stops a test that checks an error state from waiting through three retries with backoff. And letting the test choose the provider's starting value (user here) makes "signed in" and "signed out" one argument apart, instead of driving a login form in every test.
The same wrapper works for hooks: renderHook(() => useCart(), { wrapper: Wrapper }). To test a provider itself, render it with a tiny consumer that shows its value, then interact with it like a user:
it("logs in and out", async () => {
const user = userEvent.setup();
render(<AuthProvider><Navbar /></AuthProvider>);
await user.click(screen.getByRole("button", { name: "Log in as Ada" }));
expect(screen.getByText(/signed in as ada/i)).toBeInTheDocument();
});And test the guard: a hook like useAuth that throws outside its provider deserves one test that renders it without the provider and expects the error message.
Accessibility checks with axe
Querying by role and label already pushes you toward accessible markup. axe-core goes further: it scans rendered HTML against a large set of WCAG rules and reports violations such as an image without alt text, an input without a label, a button with no accessible name, duplicate ids, or invalid ARIA.
In component tests you run it against the container with a matcher package (vitest-axe and jest-axe both provide toHaveNoViolations; check the one your team uses for setup):
import { axe } from "vitest-axe";
it("has no detectable accessibility violations", async () => {
const { container } = render(<SignupForm />);
expect(await axe(container)).toHaveNoViolations();
});In end-to-end tests, @axe-core/playwright scans the real page, including the real CSS, which matters for rules like colour contrast that jsdom cannot evaluate:
import AxeBuilder from "@axe-core/playwright";
import { expect, test } from "@playwright/test";
test("checkout page has no WCAG A/AA violations", async ({ page }) => {
await page.goto("/checkout");
const results = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa"]).analyze();
expect(results.violations).toEqual([]);
});Know the limit: automated tools catch only part of accessibility problems. They cannot tell whether focus moves to the dialog when it opens, whether the tab order makes sense, or whether an error is announced. Cover those with keyboard tests: await user.tab() and expect(button).toHaveFocus(), await user.keyboard("{Escape}") to close a dialog, and assertions that an error has role="alert". An axe scan plus a few keyboard tests per interactive component is a solid, realistic baseline.
Component tests in a real browser
jsdom is fast, but it is not a browser. It has no layout (every element measures 0 by 0), no real CSS, no IntersectionObserver, and its events are simulations. Components that depend on layout, scrolling, focus behaviour, or canvas are hard to test there honestly.
Two tools run component tests in a real browser while keeping the speed of a component test:
- Vitest Browser Mode, stable since Vitest 4, runs your tests in Chromium, Firefox, or WebKit through a provider such as Playwright. You render with
vitest-browser-reactand query with locators similar to Playwright's; interactions are real browser events. - Playwright Component Testing (
@playwright/experimental-ct-react) mounts components inside Playwright's runner. It is still marked experimental, so many teams prefer Browser Mode for new work.
import { render } from "vitest-browser-react";
import { page } from "vitest/browser";
import { expect, it } from "vitest";
import { Tooltip } from "./Tooltip";
it("shows the tooltip above the button", async () => {
await render(<Tooltip text="Copied!"><button>Copy</button></Tooltip>);
await page.getByRole("button", { name: "Copy" }).hover();
await expect.element(page.getByRole("tooltip")).toBeVisible();
});Import paths and the config shape changed between Vitest 3 and 4, so copy setup from the current Vitest docs rather than an old blog post. A common split at work: jsdom for most component tests, Browser Mode for the handful that need layout or real events, and Playwright end-to-end tests for journeys.
What to put in CI
Continuous integration is where tests earn their keep: every pull request gets the same checks, and a red build blocks the merge. A typical React pipeline, cheapest and fastest checks first so failures come back quickly:
Put a typical pull-request pipeline in order, fastest feedback first.
- Tap the steps below in the right order.
Habits that keep a pipeline trustworthy:
- Run Vitest with
--runin CI so it does not start watch mode, and fail onconsole.errorif your team agrees, since React reports many bugs there. - Retries only for end-to-end tests, and only on CI, with Playwright's trace recorded on the first retry. A retry that passes is a flaky test to fix, not a success; track them.
- Coverage as a floor, not a goal. A threshold stops coverage dropping without anyone noticing. Chasing 100% produces tests that execute lines without checking behaviour.
- Quarantine, then fix. When a test turns flaky, mark it as skipped with a ticket link the same day, rather than letting it train the team to ignore red builds.
- Keep it fast. If the pipeline takes 30 minutes, people batch changes and stop running it locally. Shard end-to-end tests and cache dependencies.
Practice: build to the spec
In the challenge, the tests are written first, Testing Library style: they find the field by its label and the button by its name. Your job is to build a component that passes. This is how test-driven development feels.
A sign-up form that passes the tests
Our test suite (shown as the checks) uses Testing Library style queries: it finds the field by its label and the button by its text, then checks what a user would see. Build a component that passes.
- A
<form noValidate>(so the browser's own popup does not block your validation). - A
<label>with the textEmail, connected to an<input>(withhtmlFor+id, or by nesting the input in the label). - A submit button: Sign up.
- On submit, if the value has no
@, showEnter a valid email addressin an element withrole="alert". - Otherwise, replace the form with a message containing
Thanks!and the email, for exampleThanks! Check ada@example.com for a confirmation link.
- Vitest
- A Vite-native test runner with a Jest-compatible API (
describe,it,expect). - React Testing Library
- Renders components and queries them by role, label, and text, the way users find things.
- userEvent
- Simulates realistic user interactions (click, type, keyboard), firing the full event sequence.
- MSW
- Mock Service Worker: intercepts network requests in tests (and dev) and returns fixture responses.
- Playwright
- An end-to-end framework that drives real Chromium, Firefox, and WebKit browsers against your running app.
- findBy queries
- Async queries that retry until an element appears, used for loading and fetched content.
- flaky test
- A test that sometimes passes and sometimes fails with no code change, usually because of timing or shared state.
- waitFor
- Retries an assertion until it passes or times out. Use it for conditions other than an element appearing.
- custom render
- A shared test helper that wraps components in the app's providers (router, query client, auth) before rendering.
- axe-core
- An accessibility engine that scans rendered HTML for WCAG violations, used from Vitest or Playwright.
- Vitest Browser Mode
- Runs Vitest tests in a real browser through a provider such as Playwright, instead of jsdom.