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 (withacthandled for you).screenqueries:getBy*throws if not found (for elements that must exist).queryBy*returnsnull(to assert absence).findBy*returns a promise (waits for async elements).
- Query priority:
ByRole(withname),ByLabelText,ByPlaceholderText,ByText,ByDisplayValue, thenByTestIdas a last resort. userEvent.setup()thenawait user.click(),user.type(),user.keyboard(): realistic event sequences.waitFor(() => expect(...))for async assertions.renderHook()for testing custom hooks.@testing-library/jest-dommatchers such astoBeInTheDocument,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
1// login-form.test.tsx2import { render, screen } from "@testing-library/react";3import userEvent from "@testing-library/user-event";4import { expect, test, vi } from "vitest";5import { LoginForm } from "./login-form";67test("submits email and password", async () => {8 const user = userEvent.setup();9 const onLogin = vi.fn().mockResolvedValue(undefined);10 render(<LoginForm onLogin={onLogin} />);1112 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 }));1516 expect(onLogin).toHaveBeenCalledWith({ email: "ada@example.com", password: "correct horse battery" });17});1819test("shows an error for an invalid email", async () => {20 const user = userEvent.setup();21 render(<LoginForm onLogin={vi.fn()} />);2223 await user.type(screen.getByLabelText(/email/i), "not-an-email");24 await user.click(screen.getByRole("button", { name: /sign in/i }));2526 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.