Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 132 ยท Testing and Quality

Testing React Components

Learn how to test React components the way users use them - what to test, React Testing Library queries by role, act, async testing with findBy, and a runnable hand-rolled test harness.

Tests are how you change code without fear. A good component test tells you within a second that a refactor broke the checkout button; a bad one fails every time you rename a variable and teaches you to ignore red. The difference is not the tool (Vitest, Jest, Testing Library) but what you choose to check.

This lesson teaches the philosophy first (test behavior, the way a user experiences the component), then the vocabulary of React Testing Library (RTL): render, query, interact, wait. Because the editor cannot install packages, the runnable examples use a small test harness written from scratch (about a hundred lines). It uses the same ideas and the same React feature, act, that real libraries use, so you will understand what render and screen actually do. Real RTL code appears in clearly labelled read-only blocks.

What should you test?

Think of a component as a black box with inputs (props, user actions, network responses, context) and outputs (what appears on screen, calls to callbacks you passed in, requests sent). Good tests drive the inputs and check the outputs.

Test this Not this
"After I click Add, the cart shows 1 item" "setItems was called with an array"
"Submitting an empty form shows an error message" "The error state variable equals 'required'"
"onSave is called with the form values" "The component re-rendered twice"
"A disabled button cannot be activated" "The button has the CSS class btn-disabled"

The rule of thumb behind Testing Library: the more your tests resemble the way your software is used, the more confidence they give you. A user does not know that you use useState or useReducer, so your test should not either. If you can swap the implementation without touching the tests and they still pass, the tests are good.

The testing pyramid, in practice

  • Pure logic (formatters, reducers, validators): plain unit tests, very fast, many of them. See Testing Hooks, Reducers and Custom Logic.
  • Components (this lesson): render in a simulated DOM, interact, assert. Hundreds can run in seconds.
  • End-to-end (Playwright, Cypress): a real browser against a real or staged app; slow but they prove the whole thing works. See End-to-End and Accessibility Testing.

Most of your confidence should come from component-level tests of important behavior, plus a handful of end-to-end tests of the critical journeys (sign up, pay).

The tools in a typical project

Terminal
# read-only: the usual setup in a Vite project
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom
  • Vitest (or Jest) finds *.test.jsx files and runs them.
  • jsdom (or happy-dom) provides a fake browser DOM inside Node.
  • @testing-library/react gives render, screen and queries.
  • @testing-library/user-event simulates realistic typing and clicking.
  • @testing-library/jest-dom adds matchers like toBeDisabled() and toHaveTextContent().

A real test then looks like this. It is a read-only sketch because the editor has none of these packages:

JSX
// Counter.test.jsx  (read-only: needs Vitest and Testing Library)
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { expect, test } from 'vitest';
import { Counter } from './Counter';

test('increments when the button is pressed', async () => {
  const user = userEvent.setup();
  render(<Counter />);

  expect(screen.getByText('Count: 0')).toBeInTheDocument();

  await user.click(screen.getByRole('button', { name: /increase/i }));

  expect(screen.getByText('Count: 1')).toBeInTheDocument();
});

Every RTL test has the same four moves: arrange (render), find (queries on screen), act (user events), assert (matchers). Our harness reimplements all four.

A hand-rolled harness

Study the code below once; the following examples reuse it. The pieces:

  • test(name, body) runs a test, records PASS or FAIL with the error message, and cleans up the DOM afterwards.
  • expect(value) offers a few matchers that throw on mismatch.
  • render(ui) creates a container in document.body and renders into it with createRoot, wrapped in act.
  • screen.getByRole, getByText and friends search the DOM; the findBy... variants wait.
  • user.click and user.type dispatch real DOM events, also wrapped in act.

What is act? React batches state updates and runs effects shortly after rendering. A test needs to know when that work is finished before it looks at the DOM. await act(async () => { ... }) runs your code, then waits until React has processed all resulting renders and effects. The flag IS_REACT_ACT_ENVIRONMENT tells React "you are inside a test, warn me if an update happens outside act". Real RTL wraps every call in act for you.

A tiny testing library and the first tests

All four tests pass. Try breaking the component (change count + step to count + 2) and run again to see a failure; the harness reports uses the step prop and the second test with the message from expect.

Query by what the user perceives

The most important RTL habit is how you find elements. Prefer queries that mirror how a user or an assistive technology finds things, in this order:

  1. getByRole(role, { name }): the best default. Buttons, links, headings, text boxes, checkboxes all have roles, and the accessible name is the visible label. If you cannot find an element by role, a screen reader user may not be able to find it either, so a failed query often reveals a real accessibility bug.
  2. getByLabelText: for form fields, via their <label>.
  3. getByPlaceholderText, getByText, getByDisplayValue: for content that has no role or label.
  4. getByAltText, getByTitle: images and titled elements.
  5. getByTestId: the escape hatch (data-testid="..."). Users cannot see test ids, so use it only when nothing else works.

Each query comes in three families:

Family Not found Use for
getBy... throws immediately Elements that must be there now
queryBy... returns null Asserting something is absent
findBy... waits, then throws Elements that appear after async work

(getAllBy, queryAllBy, findAllBy return arrays.) The next example uses a profile form and shows the queries, the null from a missing element, and the helpful message a failed query produces.

Queries by role, label and text

The last line of the report prints the message Unable to find role "button" with name Delete. Roles on the page: heading, textbox, checkbox, button, link. Real RTL prints an even longer message that lists every accessible element and its name, which is the quickest way to debug a failing query.

Use the exact visible text for names. Testing getByRole('button', { name: 'Save' }) documents what the user sees. Use a regular expression with the i flag (/save/i) when casing or surrounding text may vary. Avoid translating your tests to CSS selectors: container.querySelector('.btn-primary') ties the test to styling.

Forms, callbacks and async UI

Components talk to the outside through callback props and async calls. Test them by providing fakes:

  • For a callback, pass a spy, a function that records its calls. In Vitest it is vi.fn(); in our harness a plain array does the job.
  • For data loading, pass a function that returns a promise you control (or mock the network layer; MSW is the usual tool that intercepts requests at the network boundary).

For async UI, never await an arbitrary timeout like setTimeout(500). Use a findBy query or waitFor, which polls (inside act) until the element appears or a timeout passes. Fast tests stay fast and slow machines do not cause flakes.

A form with a spy and async loading

The real-library versions of those two kinds of tests look like this (read-only):

JSX
// read-only: Vitest + Testing Library + MSW
test('shows the user from the API', async () => {
  server.use(http.get('/api/user', () => HttpResponse.json({ name: 'Ada Lovelace' })));
  render(<UserCard />);

  expect(screen.getByText(/loading/i)).toBeInTheDocument();
  expect(await screen.findByRole('heading', { name: 'Ada Lovelace' })).toBeInTheDocument();
});

test('calls onSubmit with the typed email', async () => {
  const user = userEvent.setup();
  const onSubmit = vi.fn();
  render(<SignupForm onSubmit={onSubmit} />);

  await user.type(screen.getByLabelText('Email'), '[email protected]');
  await user.click(screen.getByRole('button', { name: 'Sign up' }));

  expect(onSubmit).toHaveBeenCalledWith({ email: '[email protected]' });
});

Tests that survive refactoring

Here is the payoff of testing behavior. The next example has two implementations of a toggle switch: one with useState and CSS classes, one with useReducer and different markup. Two tests exist for each. The behavior test clicks the switch and checks aria-checked, which is what users and assistive technology see. The brittle test reaches into the DOM structure and class names.

Behavior tests versus brittle tests

Both behavior tests pass, and the brittle test fails for V2 with expected "switch on" but got "wrapper". Nothing the user can see or do changed, yet one test broke: that is the cost of testing implementation details. Over a year of refactoring, brittle tests either get deleted or train the team to distrust failures.

act, and the warning that confuses everyone

If a state update happens outside act while React believes it is in a test, it prints a warning. The usual cause is an unawaited asynchronous update: a timer, a promise or an event that fires after the test finished waiting. This example triggers it on purpose:

State update outside act (fails on purpose)

The console shows right after render: waiting, then later: done, and React's error An update to Delayed inside a test was not wrapped in act(...). The state did update, but the test was not watching in the way React requires. The cure is to wait with something act-aware: await screen.findBy..., await waitFor(...), or put the waiting inside await act(async () => { ... }). Never silence the warning by disabling the flag.

Practical advice

  • One behavior per test, named as a sentence ("shows an error when the email has no @").
  • Arrange only what the test needs. Use small factory functions for props and fake data.
  • Mock at the edges: the network, the clock, window.matchMedia. Do not mock your own components or hooks unless you have to; real children give real confidence.
  • Test accessibility for free with role queries, and add jest-axe or Playwright accessibility checks for page-level rules.
  • Do not chase 100% coverage. Cover logic and journeys that matter. Coverage numbers measure lines executed, not behavior verified.
  • Snapshots of large rendered trees are noisy; prefer explicit assertions. Small, focused snapshots of stable output (like a formatted string) are fine. More in the next lesson.
  • Keep tests independent. Each test renders its own tree and cleans up; shared mutable state between tests causes order-dependent failures.
  • Test the contract of context-dependent components by wrapping them in a provider helper (a renderWithProviders function), covered in the next lesson.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which test is closest to the Testing Library philosophy?

    Users see output and perform actions. Tests that do the same keep passing when you refactor the internals.
  2. 2. You need to assert that an error message is NOT on the screen. Which query fits?

    queryBy queries return null instead of throwing, which makes them the right tool for absence checks.
  3. 3. Why prefer getByRole('button', { name: 'Save' }) over container.querySelector('.btn-save')?

    Role and name are part of the user-facing contract (and accessibility). Class names are an implementation detail.
  4. 4. A message loads from the network after 200 ms. How should the test wait for it?

    findBy queries retry until the element appears or a timeout passes, so tests are as fast as the UI and not flaky.
  5. 5. What does act() do in a React test?

    act flushes renders, state updates and effects so assertions see the final UI. Testing Library wraps its helpers in act for you.

Summary

  • Test behavior from the user's point of view: what is on screen, what callbacks receive, what requests go out. Avoid asserting state, render counts or class names.
  • Every test follows arrange, find, act, assert. Libraries add render, screen queries and user-event.
  • Find elements by role and accessible name first, then label, text and finally test ids; failed role queries often reveal accessibility problems.
  • getBy throws, queryBy returns null (for absence), findBy waits (for async UI).
  • Pass spies for callbacks and promises you control for data; mock at the network boundary.
  • act makes React finish rendering and effects before you look at the DOM; warnings about updates outside act mean your test is not waiting properly.
  • Behavior-focused tests survive refactors; brittle tests cost more than they give.

Next: Testing Hooks, Reducers and Custom Logic