Skip to content

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.

19 min read0/6 questions

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.

Frontend testing pyramid
  1. End-to-end (Playwright)a real browser drives the whole app: few, slow, highest confidence
  2. Integration / component (Vitest + Testing Library)render components, click, check the screen: the bulk of your tests
  3. Unit (Vitest)pure functions, reducers, hooks: many, milliseconds each
  4. Static (TypeScript, ESLint)catches typos and wrong types before anything runs

The base is free: TypeScript and ESLint catch a whole class of bugs on every save.

1/4

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-dom
vite.config.ts
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
 
export default defineConfig({
  plugins: [react()],
  test: {
    environment: "jsdom",
    setupFiles: "./src/test/setup.ts",
  },
});
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.

ReactCounter.tsx
import { useState } from "react"; export default function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> <button onClick={() => setCount(0)} disabled={count === 0}>Reset</button> </div> );}
Counter.test.tsx
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.
  • userEvent simulates 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-level fireEvent.
  • Matchers like toBeInTheDocument() and toBeDisabled() come from @testing-library/jest-dom.
Match the pairs0/4 matched

Match the query to when you use it.

Choose an item, then its match on the other side.

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);

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.

Quick check
You refactor a form from three useState calls to one useReducer. The UI is identical. Which test should still pass?
Need a nudge? A hint rules out a wrong answer.

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.

TypeScriptmini-testing-library.ts
type Node = { role: string; name: string; disabled?: boolean }; const screen: Node[] = [ { role: "heading", name: "Sign up" }, { role: "textbox", name: "Email" }, { role: "button", name: "Sign up", disabled: false }, { role: "button", name: "Cancel" },]; function getByRole(role: string, opts: { name: string }): Node { const matches = screen.filter((n) => n.role === role && n.name === opts.name); if (matches.length !== 1) throw new Error(`Found ${matches.length} ${role} named "${opts.name}"`); return matches[0];} function queryByRole(role: string, opts: { name: string }): Node | null { return screen.find((n) => n.role === role && n.name === opts.name) ?? null;} console.log(getByRole("button", { name: "Sign up" }));console.log(queryByRole("button", { name: "Delete" })); // null: asserting absencetry { getByRole("button", { name: "Submit" });} catch (e) { console.log((e as Error).message); // get* throws a helpful error}
Output
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.

src/test/server.ts
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());
TodoList.test.tsx
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");
});
A component test with MSW
TestComponentfetchMSWrender(<TodoList />)GET /api/todosintercepted200 JSON fixturefindByRole("listitem")

The test mounts the component in jsdom. It shows Loading....

1/5

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.

e2e/signup.spec.ts
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 debugger
Put it in order5 steps

Put the steps of a typical component test in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Quick check
Which test belongs in Playwright rather than Vitest?
Need a nudge? A hint rules out a wrong answer.

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 is getBy plus 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.

TypeScriptmini-waitFor.ts
async function waitFor<T>(check: () => T, { timeout = 1000, interval = 50 } = {}): Promise<T> { const start = Date.now(); let lastError: unknown; while (Date.now() - start < timeout) { try { return check(); // passes: stop waiting } catch (e) { lastError = e; // fails: wait a bit and try again } await new Promise((r) => setTimeout(r, interval)); } throw lastError;} // A fake "screen" whose text changes after 200 ms, like a fetch finishing.let screenText = "Loading...";setTimeout(() => (screenText = "3 todos"), 200); let attempts = 0;const result = await waitFor(() => { attempts += 1; if (screenText !== "3 todos") throw new Error(`Still showing: ${screenText}`); return screenText;});console.log(result, "after about", attempts, "attempts"); try { await waitFor(() => { throw new Error("Never shows Done"); }, { timeout: 200 });} catch (e) { console.log("timed out with the last error:", (e as Error).message);}
Output
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 waitFor with getBy to wait for an element. Use findBy, 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:

SearchBox.test.tsx
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.

Quick check
Which of these is the most reliable way to check that an error message appears after a failed request?
Need a nudge? A hint rules out a wrong answer.

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:

src/test/test-utils.tsx
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):

SignupForm.test.tsx
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:

e2e/a11y.spec.ts
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-react and 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.
Tooltip.browser.test.tsx
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 it in order5 steps

Put a typical pull-request pipeline in order, fastest feedback first.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Habits that keep a pipeline trustworthy:

  • Run Vitest with --run in CI so it does not start watch mode, and fail on console.error if 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.

ChallengeMedium

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 text Email, connected to an <input> (with htmlFor + id, or by nesting the input in the label).
  • A submit button: Sign up.
  • On submit, if the value has no @, show Enter a valid email address in an element with role="alert".
  • Otherwise, replace the form with a message containing Thanks! and the email, for example Thanks! Check ada@example.com for a confirmation link.
React
import { useState } from "react"; export default function App() { // A labelled email field, a Sign up button, an alert for errors, and a thank-you message. return <form noValidate></form>;}
Key terms
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.