Testing components with React Testing Library

Intermediate · 48 min

RTL's "test like a user" philosophy, the getByRole query order, user-event for realistic interactions, and mocking a fetch call.

Before thisCustom hooksForms and controlled inputs

RoadsideCoder · 48 min

Testing components with React Testing Library

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by RoadsideCoderReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • React Testing Library's core philosophy is to test components the way a user experiences them, through visible text, roles, and labels, never through internal state or instance methods.
  • Queries have a preferred order, and getByRole sits at the top because it matches how assistive technology and most sighted users actually find things on a page.
  • user-event simulates a full, realistic interaction (focus, pointer events, then the actual key or click), unlike the lower-level fireEvent, which only fires a single synthetic event.
  • A query that fails to find anything throws immediately with a readable error, which is why tests read like a specification of what the user can see and do.
  • Mocking a fetch call isolates a component's rendering and interaction logic from the network, so the test is fast, deterministic, and doesn't depend on a real server being up.
  • Tests that assert on CSS classes, prop values, or component internals break every time you refactor the implementation, even when the user-facing behavior hasn't changed — RTL is deliberately built to make that kind of test hard to write.

Test like a user, not like the implementation

React Testing Library (RTL) is built around one opinionated idea: a test should interact with your component the same way a person using the app would — by reading visible text, finding a button by its accessible role, and typing into a field — rather than by reaching into component internals like state variables, props, or class names.

The reasoning is practical, not philosophical. A test that asserts wrapper.state.isOpen === true breaks the moment you refactor from useState to useReducer, even though nothing about what the user sees changed. A test that asserts the modal’s heading is visible on the screen survives that refactor, because the user-facing behavior didn’t change. RTL’s API makes the second kind of test the easy, natural one to write, and makes the first kind awkward on purpose — there is no official way to read a component’s internal state from a test.

Queries, in preference order

RTL’s queries all search the rendered DOM, but they differ in what they search by, and the library’s own documentation ranks them by how closely they match how a real user or assistive technology finds things:

import { render, screen } from "@testing-library/react";

render(<LoginForm />);

// 1. Preferred: matches the accessibility tree, same as a screen reader would.
screen.getByRole("button", { name: /sign in/i });
screen.getByRole("textbox", { name: /email/i });

// 2. Good fallback for form fields: matches a <label>.
screen.getByLabelText(/password/i);

// 3. Fine for visible copy with no interactive role.
screen.getByText(/forgot your password\?/i);

// 4. Last resort: an opaque hook with no user-facing meaning.
screen.getByTestId("login-form-root");

getByRole sits at the top because almost everything interactive already has an implicit role — a <button> is role button, an <input type="checkbox"> is role checkbox — so querying by role doubles as a check that your markup is semantic and accessible. getByTestId works but tells you nothing about whether a real user, or a screen reader, could find that element at all; reach for it only when no honest query fits.

Each query family comes in three forms: getBy... throws if nothing matches (use it when the element should already be there), queryBy... returns null instead of throwing (use it to assert something is absent), and findBy... returns a promise that resolves once the element appears (use it for anything that shows up after an async update).

user-event over fireEvent

fireEvent dispatches exactly the DOM event you name. user-event simulates what actually happens when a person uses the keyboard or mouse — a click fires pointer-down, focus, pointer-up, and click events in the right order; typing into a field fires one keystroke event per character, updating the value incrementally rather than in one jump.

import userEvent from "@testing-library/user-event";
import { render, screen } from "@testing-library/react";

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

  await user.type(screen.getByRole("textbox", { name: /email/i }), "a@b.com");
  await user.click(screen.getByRole("button", { name: /sign in/i }));

  expect(onSubmit).toHaveBeenCalledWith("a@b.com");
});

This matters because some bugs only show up under the realistic sequence — a field that only validates on blur, for instance, will pass a fireEvent.change test but needs the focus-then-blur sequence user-event produces naturally.

Mocking a fetch call

A component that fetches data shouldn’t depend on a real network during a test. Mocking the fetch call keeps the test fast and gives you control over exactly what the component receives:

test("shows the user's name once the profile loads", async () => {
  vi.spyOn(global, "fetch").mockResolvedValue({
    ok: true,
    json: async () => ({ name: "Ada Lovelace" }),
  });

  render(<Profile userId="42" />);

  expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument();
});

findByText is used here, not getByText, because the name only appears after the mocked promise resolves and the component re-renders.

What the video covers

RoadsideCoder’s course builds a full testing setup around a real app: configuration, queries, user-event-based interaction, mocking API calls, and testing a custom hook, using Vitest rather than Jest (the RTL API itself is identical either way). It’s thorough but doesn’t explicitly state the “test like a user” philosophy in words — that framing, and the query preference order specifically, is what this lesson adds around it.

Where this fits

Testing depends on knowing how to build forms and hooks, which is why those are the prerequisites here. Next: typing props, state, and hooks with TypeScript.

Check yourself

  1. 01Why does React Testing Library discourage selecting elements by CSS class or component display name?

    Because a class name or component name is an implementation detail invisible to a user; testing against it makes the test brittle to refactors that change nothing a user would notice, which is the opposite of what a good test should verify.

  2. 02In what order should you prefer RTL's queries, and why does getByRole usually come first?

    The recommended order is roughly getByRole, then getByLabelText, getByPlaceholderText, getByText, and getByTestId last; getByRole comes first because it reflects how the accessibility tree exposes the element, meaning a test that passes with it also demonstrates the markup is accessible.

  3. 03What is the practical difference between fireEvent.click and userEvent.click on the same button?

    fireEvent.click dispatches a single synthetic click event, while userEvent.click simulates the fuller sequence a real user triggers, including pointer and focus events, which catches bugs that depend on that sequence, such as a handler that only runs correctly after the element received focus.

  4. 04When a component calls fetch to load data, what does mocking that call in a test let you control that a real network request would not?

    Mocking lets the test control exactly what response comes back, including edge cases like an error status or an empty list, on demand and without waiting on or depending on a real backend being reachable.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark