Testing

Testing Library, Vitest, MSW and Playwright.

Builds on Custom hooks.

A test suite is worth exactly as much confidence as it gives you per minute of upkeep. React projects get this wrong in two opposite ways: no tests, or thousands of tests that check how components are built (which state variable changed, which child got which prop) and break on every refactor while missing the bugs users hit.

This chapter is about writing the other kind. We'll start with what a React test actually has to do (render into a DOM, interact, wait for React to finish), build a tiny render function to see it, then go through the real stack: Vitest, React Testing Library and its philosophy, user-event, MSW for the network, renderHook and act(), and Playwright for end-to-end tests. It ends with what not to test, which is half the skill.

The problem: tests that check the wrong thing#

Imagine a search box. One way to test it is to reach inside: assert that after typing, the component's query state is "craft", that a fetchBooks function was called once, that the Results child received an array of three. Each of those is an implementation detail. Rename the state, move the fetch into a custom hook, switch to TanStack Query, and every test fails even though the feature works. Meanwhile none of them notices that the input has no label, so screen reader users can't find it, or that results never appear because the response handling is broken.

The user of a component doesn't see state or props. They see text, roles and labels, and they type, click and wait. React Testing Library's guiding principle puts it in one line: the more your tests resemble the way your software is used, the more confidence they can give you. A good component test reads like a description of using the screen.

Build it: what render() has to do#

Before using a library, it's worth seeing how little there is to the code that runs a component test. A test needs to mount a component into a real DOM (jsdom in Node, or a browser), make sure React has finished rendering, interact, and wait for asynchronous updates. The only subtle part is the "finished" part, and that's what act() is for.

act(callback) runs the callback and then flushes everything React queued because of it: renders, effects, state updates. Without it, your assertion can run before React has committed the result. React 19 exports act from react (the old react-dom/test-utils is gone apart from a deprecated act re-export), and it warns you about updates outside act if you set the global IS_REACT_ACT_ENVIRONMENT flag, which testing libraries do for you.

Here are about fifty lines with the same shape as React Testing Library, then a component and three tests. The queries (screen, waitFor) and the base user come from this guide's guide-tools, a small module that mirrors Testing Library's API; the render, cleanup and act-wrapped user are built here. Run it and read the console.

A tiny React Testing Library
import { expect, screen } from "guide-tools";
import { render, user, waitFor, it, run } from "./test-utils";
import { SearchBooks } from "./SearchBooks";

it("doesn't show results before a search", () => {
  render(<SearchBooks />);
  expect(screen.queryAllByRole("listitem")).toHaveLength(0);
});

it("shows matching books", async () => {
  render(<SearchBooks />);
  await user.type(screen.getByLabelText("Search"), "craft");
  await user.click(screen.getByRole("button", { name: "Search" }));
  await waitFor(() => expect(screen.queryAllByRole("listitem")).toHaveLength(4)); // three tagged "craft", plus "Crafting Interpreters"
  expect(screen.getByText("Refactoring")).toBeTruthy();
});

it("says so when nothing matches", async () => {
  render(<SearchBooks />);
  await user.type(screen.getByLabelText("Search"), "zzz");
  await user.click(screen.getByRole("button", { name: "Search" }));
  await waitFor(() => expect(screen.getByText("No books match “zzz”.")).toBeTruthy());
});

run();
Nothing logged yet.

Try breaking the component and watch the right test fail: remove the <label>, change "Search" on the button, or return early on an empty result. Then try refactoring it without changing behavior, say by moving the fetch into a useBookSearch hook: every test still passes. That asymmetry is what you want.

Three things this toy does that the real library also does:

  • Mount into document.body, and clean up after each test. Tests must not see each other's DOM.
  • Wrap renders and interactions in act(), so React has committed and run effects before the next line.
  • Poll for asynchronous results with waitFor, instead of guessing a delay.

The real stack#

Where React tests go
End to endPlaywrightCatchesreal browser and server, key flowsIntegrationVitest + Testing Library + MSWCatchesa screen with real childrenUnitVitestCatcheslogic, reducers, custom hooksStaticTypeScript + ESLintCatches without runningtypos, wrong props, hook rules
The testing trophy: widths are roughly how much of your effort each layer deserves. Most confidence per minute comes from integration tests that render real component trees and interact the way a user does.

Vitest (current major: 5) is the default test runner for Vite-based projects and works fine for others: Jest-compatible API (describe, it, expect, vi.fn), native ESM and TypeScript through the same transform pipeline as your app, and a fast watch mode. Jest (30) is still everywhere in older codebases and works the same way conceptually. Component tests run in jsdom or happy-dom, simulated DOMs inside Node. Vitest's Browser Mode (stable since Vitest 4) runs the same tests in a real browser through Playwright when jsdom's gaps matter (layout, real focus behavior, CSS).

A typical setup:

vitest.config.ts
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  test: {
    environment: "jsdom",
    setupFiles: ["./vitest.setup.ts"],
  },
});

React Testing Library: queries are the philosophy#

React Testing Library (RTL, @testing-library/react 16) gives you render and re-exports @testing-library/dom's queries. The queries are where the philosophy lives. They find elements the way users and assistive technology do, and the docs give an explicit priority:

  1. getByRole with a name: getByRole("button", { name: "Add" }), getByRole("textbox", { name: "Search" }), getByRole("heading", { level: 2 }). Roles come from the accessibility tree, so this query only passes if the element is exposed correctly to screen readers. It's an accessibility check you get for free.
  2. getByLabelText for form fields, getByPlaceholderText if there's truly no label, getByText for non-interactive content, getByDisplayValue for filled inputs.
  3. getByAltText, getByTitle.
  4. getByTestId as the escape hatch, when there's no user-facing way to find something.

Each comes in three variants that encode intent: getBy throws if the element isn't there (use it for things that must exist now), queryBy returns null (use it to assert absence), and findBy returns a promise that retries until the element appears or a timeout (use it for anything asynchronous). findBy is waitFor plus getBy.

user-event: interactions as a user performs them#

fireEvent.click(button) dispatches one event. A real click is a sequence: pointer down, mouse down, focus moves, pointer up, mouse up, click. Typing a character is keydown, keypress, beforeinput, input, keyup, with the cursor position and maxlength respected. @testing-library/user-event (14) simulates the whole sequence, so bugs that depend on focus or on event order show up in tests.

The static tests from here on target the app's real SearchBooks: the same form, but it fetches https://api.example.com/books?q=... and shows a role="alert" message, "Search failed", when the request fails. The MSW handlers in the next section answer those requests.

SearchBooks.test.tsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test } from "vitest";
import { SearchBooks } from "./SearchBooks";

test("shows matching books", async () => {
  const user = userEvent.setup(); // before render
  render(<SearchBooks />);

  await user.type(screen.getByRole("textbox", { name: "Search" }), "craft");
  await user.click(screen.getByRole("button", { name: "Search" }));

  expect(await screen.findAllByRole("listitem")).toHaveLength(2); // the two "craft" books in the MSW handler
  expect(screen.getByText("Refactoring")).toBeInTheDocument();
});

Every user-event call is async and already wrapped in act() by RTL, so you await it and never write act yourself here.

Mocking the network with MSW#

The component fetches. In a test you don't want a real server, but you also don't want to mock fetch or your data-fetching hook, because then you're testing your mock. Mock Service Worker (MSW, currently 3.x) intercepts requests at the network layer: in the browser through a Service Worker, in Node by hooking the request modules. Your component, TanStack Query, axios, whatever, all run unmodified and receive real Response objects.

src/mocks/handlers.ts
import { http, HttpResponse } from "msw/http";

export const handlers = [
  http.get("https://api.example.com/books", ({ request }) => {
    const q = new URL(request.url).searchParams.get("q") ?? "";
    const all = [
      { id: 1, title: "The Pragmatic Programmer", tags: ["craft"] },
      { id: 3, title: "Refactoring", tags: ["craft"] },
      { id: 7, title: "Thinking in Systems", tags: ["systems"] },
    ];
    return HttpResponse.json(all.filter((b) => b.tags.includes(q)));
  }),
];

The same handlers can run in the browser during development and in Storybook, so one description of your API serves dev, stories and tests. onUnhandledRequest: "error" in the setup makes any request without a handler fail loudly, which catches tests silently hitting a real endpoint.

Testing hooks with renderHook#

Most hooks are best tested through a component that uses them, because that's how they run in the app. When a hook is a reusable unit with its own contract (a useDebounce, a useLocalStorage), test it directly. renderHook renders a throwaway component that calls your hook and exposes the latest return value as result.current:

useCounter.test.ts
import { act, renderHook } from "@testing-library/react";
import { expect, test } from "vitest";
import { useCounter } from "./useCounter";

test("increments", () => {
  const { result, rerender } = renderHook(({ step }) => useCounter(0, step), { initialProps: { step: 1 } });
  act(() => result.current.increment()); // a state update outside a user-event call needs act
  expect(result.current.count).toBe(1);

  rerender({ step: 5 }); // new arguments, same hook instance
  act(() => result.current.increment());
  expect(result.current.count).toBe(6);
});

Here act is needed because you're calling a state setter directly, not through user-event. You'll build renderHook yourself in the exercises below.

act() and the warning everyone has seen#

"An update to SearchBooks inside a test was not wrapped in act(...)" means React rendered after your test thought it was done with that interaction. Almost always, some asynchronous work (a fetch, a timer, a promise) resolved after the test's last await. The fix is not to wrap things in act until the warning goes away. It's to wait for the outcome the user would see: await screen.findByText(...), or await waitFor(...). Then the update happens while the test is waiting for it, and the assertion checks the final state.

For timers, use fake timers (vi.useFakeTimers()) and tell user-event how to advance them: userEvent.setup({ advanceTimers: vi.advanceTimersByTime }).

End-to-end tests with Playwright#

Component tests run in a simulated DOM with a mocked network. End-to-end tests run your real app, built and served, in real browsers (Chromium, Firefox, WebKit). They're slower and more brittle, so keep them for the flows that would hurt most if they broke: sign-in, checkout, the core create-edit-delete loop. Playwright (npm init playwright@latest) uses the same query philosophy as Testing Library:

e2e/books.spec.ts
import { expect, test } from "@playwright/test";

test("add a book to the reading list", async ({ page }) => {
  await page.goto("/books");
  await page.getByLabel("Title").fill("Dune");
  await page.getByRole("button", { name: "Add" }).click();

  // Assertions auto-retry until they pass or time out: no sleeps.
  await expect(page.getByRole("listitem").filter({ hasText: "Dune" })).toBeVisible();
});

Two things make Playwright tests reliable: locators that are re-resolved on every action (so a re-render doesn't leave you holding a stale element), and web-first assertions like toBeVisible() that retry. E2E is also where Server Components get tested: Vitest and Jest can render Client Components and synchronous Server Components, but async Server Components aren't supported by those tools yet, and Next.js's own docs recommend E2E tests for them.

Cypress is the other E2E tool you'll meet, especially in codebases from before Playwright caught on. It runs your test code inside the browser next to the app and has a strong interactive runner with time-travel debugging. Playwright drives browsers from outside through their automation protocols, which makes several tabs, origins and browser engines straightforward. New projects mostly pick Playwright; the ideas (real browser, user-facing locators, retrying assertions, few but valuable tests) are the same in both.

What not to test#

The skill is choosing. Skip these:

  • Implementation details: state variable values, which hook was called, internal function calls, how many times something rendered, the component tree's shape. Test the visible result instead.
  • Styles and class names. "Has class btn-primary" tests your markup, not anything a user perceives. Use visual regression tools (Playwright screenshots, Storybook's visual testing) if appearance matters.
  • The framework and libraries. Don't test that React re-renders on state change or that TanStack Query caches. Test your use of them through behavior.
  • Things the type checker already guarantees, like "renders without crashing when given the right props".
  • Giant snapshots. A 400-line toMatchSnapshot() gets updated with -u without anyone reading it. Small inline snapshots of a specific output can be fine.

And keep at least these: every user-facing flow on important screens, each state of async UI (loading, empty, error, success), form validation messages, keyboard paths for interactive widgets, and bugs you've fixed (a regression test per bug).

Pitfalls#

Check your understanding#

Build itBuild renderHook

Implement renderHook(callback, { initialProps }). It should render a tiny component that calls callback(props) and stores the return value in result.current, and return { result, rerender, unmount }, where rerender(newProps) renders again with new props. Wrap renders in act so result.current is up to date when the function returns.

import { act, useState } from "react";
import { createRoot } from "react-dom/client";

(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;

export function renderHook<P, R>(callback: (props: P) => R, options: { initialProps?: P } = {}) {
  const result = { current: undefined as unknown as R };
  // TODO: render a component that calls callback(props) and stores the value in result.current.
  return {
    result,
    rerender(props: P) {},
    unmount() {},
  };
}

// A hook to test.
export function useCounter(initial: number, step = 1) {
  const [count, setCount] = useState(initial);
  return { count, increment: () => setCount((c) => c + step) };
}

(window as any).renderHook = renderHook;
(window as any).useCounter = useCounter;

const { result } = renderHook(() => useCounter(5));
console.log("initial count:", result.current?.count);
Nothing logged yet.
Fix itThe test can't find the form

The checks for this exercise are written the way a Testing Library test should be: they find the title field by its label and the Add control by its role and name. They fail, but not because the test is wrong. Fix the component so a user (including one with a screen reader or a keyboard) can use it, and the checks pass.

import { useState } from "react";

export default function App() {
  const [title, setTitle] = useState("");
  const [books, setBooks] = useState<string[]>([]);

  function add() {
    if (!title.trim()) return;
    setBooks([...books, title.trim()]);
    setTitle("");
  }

  return (
    <div>
      <input placeholder="Title" value={title} onChange={(e) => setTitle(e.target.value)} />
      <div className="btn" onClick={add} style={{ display: "inline-block", padding: "2px 8px", border: "1px solid #a8a29e", cursor: "pointer" }}>
        Add
      </div>
      <ul>
        {books.map((b) => (
          <li key={b}>{b}</li>
        ))}
      </ul>
    </div>
  );
}
PredictDoes this test pass?

SearchBooks fetches results after the button is clicked, with a 100 ms response time. Predict the outcome of each test.

test("A", async () => {
  const user = userEvent.setup();
  render(<SearchBooks />);
  await user.type(screen.getByRole("textbox", { name: "Search" }), "craft");
  await user.click(screen.getByRole("button", { name: "Search" }));
  expect(screen.getByText("Refactoring")).toBeInTheDocument();
});

test("B", async () => {
  const user = userEvent.setup();
  render(<SearchBooks />);
  await user.type(screen.getByRole("textbox", { name: "Search" }), "craft");
  await user.click(screen.getByRole("button", { name: "Search" }));
  expect(await screen.findByText("Refactoring")).toBeInTheDocument();
});

test("C", async () => {
  render(<SearchBooks />);
  expect(screen.queryByText("Refactoring")).toBeNull();
});
Quick checkChoosing a query

Which query should you reach for first to find a Save button?

Explain it out loudYour testing strategy

"How do you test a React component that loads data from an API and lets the user filter it?"

Interview angle

Say it in 30 seconds

Test React components the way they're used: render a real tree, find elements by role, label and text, interact with user-event, and wait for what the user would see. That's React Testing Library's philosophy, and it keeps tests green through refactors and red when behavior breaks. Mock the network with MSW instead of mocking your own hooks, use renderHook for reusable hooks, and fix act warnings by awaiting the visible outcome with findBy or waitFor. Most effort goes into integration tests with Vitest; a few Playwright tests cover critical flows and async Server Components; TypeScript and ESLint catch a class of bugs before anything runs.

What is React Testing Library's philosophy, and why does it matter?

basic

What does act() do, and what does the 'not wrapped in act' warning mean?

intermediate

What's the difference between getBy, queryBy and findBy?

basic

How would you mock API calls in component tests?

intermediate

How do you balance unit, integration and end-to-end tests in a React app?

senior

What shouldn't you test in a React codebase?

senior

Recap#

  • Test behavior the user can observe (text, roles, labels, interactions), not implementation details, so refactors keep tests green and real bugs turn them red.
  • A component test mounts into a DOM, wraps renders and interactions in act() so React finishes, and waits for async results. RTL and user-event do this for you; React 19 exports act from react.
  • Prefer getByRole with a name, then label and text queries; getBy for present, queryBy for absent, findBy for async. user-event simulates full interaction sequences.
  • Mock the network with MSW so hooks and caches run unmodified; use renderHook for reusable hooks; fix act warnings by awaiting the visible outcome.
  • Keep a few Playwright E2E tests for critical flows and async Server Components. Lean on TypeScript and ESLint at the base.

Sources#