ReactEasy

What is React Testing Library?

React Testing Library (RTL) is a set of utilities for testing React components the way users use them: you render a component, find elements by accessible role, label or text, interact with them through user-event, and assert on what appears. It deliberately avoids testing implementation details like state or internal methods. Version 16 requires @testing-library/dom as a peer dependency.

Core API

  • render(<Component />) renders into a jsdom container (with act handled for you).
  • screen queries:
    • getBy* throws if not found (for elements that must exist).
    • queryBy* returns null (to assert absence).
    • findBy* returns a promise (waits for async elements).
  • Query priority: ByRole (with name), ByLabelText, ByPlaceholderText, ByText, ByDisplayValue, then ByTestId as a last resort.
  • userEvent.setup() then await user.click(), user.type(), user.keyboard(): realistic event sequences.
  • waitFor(() => expect(...)) for async assertions.
  • renderHook() for testing custom hooks.
  • @testing-library/jest-dom matchers such as toBeInTheDocument, toBeDisabled, toHaveAccessibleName.

Philosophy

"The more your tests resemble the way your software is used, the more confidence they can give you." Tests that use roles and labels survive refactors and double as accessibility checks.

Works with

Vitest or Jest, MSW for network mocking, and providers wrapped with a custom render (router, query client, theme).

Replaces

Enzyme (unmaintained, no support for modern React) and react-test-renderer (deprecated in React 19).

Code example

tsx
1// login-form.test.tsx
2import { render, screen } from "@testing-library/react";
3import userEvent from "@testing-library/user-event";
4import { expect, test, vi } from "vitest";
5import { LoginForm } from "./login-form";
6
7test("submits email and password", async () => {
8 const user = userEvent.setup();
9 const onLogin = vi.fn().mockResolvedValue(undefined);
10 render(<LoginForm onLogin={onLogin} />);
11
12 await user.type(screen.getByLabelText(/email/i), "ada@example.com");
13 await user.type(screen.getByLabelText(/password/i), "correct horse battery");
14 await user.click(screen.getByRole("button", { name: /sign in/i }));
15
16 expect(onLogin).toHaveBeenCalledWith({ email: "ada@example.com", password: "correct horse battery" });
17});
18
19test("shows an error for an invalid email", async () => {
20 const user = userEvent.setup();
21 render(<LoginForm onLogin={vi.fn()} />);
22
23 await user.type(screen.getByLabelText(/email/i), "not-an-email");
24 await user.click(screen.getByRole("button", { name: /sign in/i }));
25
26 expect(await screen.findByRole("alert")).toHaveTextContent(/valid email/i);
27 expect(screen.queryByText(/welcome/i)).not.toBeInTheDocument();
28});

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app