Skip to content

Testing React Components

Writing unit and integration tests with React Testing Library and Jest or Vitest.

What you'll learn

  • The philosophy of React Testing Library
  • Rendering components and querying the DOM
  • Firing events and asserting on output
  • Testing async behavior and user interactions

Concept

The Testing Philosophy

React Testing Library (RTL) is built on a guiding principle: test your components the way a user would use them. Instead of testing implementation details (component internals, state shape, method calls), you test the rendered output and user interactions. This makes tests more robust to refactoring — if you change the internals but keep the behavior, the tests still pass. RTL renders the component to a real DOM (via jsdom) and provides queries to find elements.

Rendering and Querying

You render a component with render(<MyComponent />) and then query the output. RTL provides several query methods: getByText, getByRole, getByLabelText, getByTestId, and more. The recommended priority is to query by role (accessibility role like "button", "heading", "textbox") because it tests the accessible interface. getBy* throws if not found, queryBy* returns null, and findBy* is async (waits for appearance).

Firing Events

Use userEvent (from @testing-library/user-event) to simulate user interactions. It is more realistic than the lower-level fireEvent — it simulates the full interaction sequence (focus, key presses, blur) and waits for state updates. For example, await user.click(button) or await user.type(input, "hello"). Always await userEvent operations because they may trigger async state updates.

Testing Async Behavior

For components that fetch data or show content asynchronously, use findBy* queries which wait for elements to appear (with a timeout). Use waitFor to wait for an assertion to pass. For testing that an element disappears, use waitForElementToBeRemoved. For testing that an element disappears, use waitForElementToBeRemoved. Mock fetch or API modules with vi.fn() (Vitest) or jest.fn() to control what data is returned and to assert that calls were made with the right arguments.

Test Organization

Organize tests with describe blocks that group related tests by component or feature. Use clear it names that describe the expected behavior: "displays an error when the email is invalid" rather than "test1". Aim for tests that are independent — each test should set up its own state and not depend on execution order. Use beforeEach for common setup. Keep tests fast by mocking network calls and avoiding real timers.

Example

              import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi } from "vitest";
import LoginForm from "./LoginForm";

describe("LoginForm", () => {
  it("shows an error for invalid email", async () => {
    const user = userEvent.setup();
    render(<LoginForm />);

    // Query by role — tests the accessible interface.
    const emailInput = screen.getByRole("textbox", { name: /email/i });
    const submitButton = screen.getByRole("button", { name: /submit/i });

    // Simulate user typing and clicking.
    await user.type(emailInput, "not-an-email");
    await user.click(submitButton);

    // Assert the error message appears.
    expect(screen.getByText(/valid email required/i)).toBeInTheDocument();
  });

  it("submits with valid input", async () => {
    const onSubmit = vi.fn();
    const user = userEvent.setup();
    render(<LoginForm onSubmit={onSubmit} />);

    await user.type(screen.getByLabelText(/email/i), "test@example.com");
    await user.click(screen.getByRole("button", { name: /submit/i }));

    expect(onSubmit).toHaveBeenCalledWith({ email: "test@example.com" });
  });
});
            

Tests query by role (accessible interface), use userEvent for realistic interactions, and assert on visible output — not implementation details. This makes tests robust to refactoring.

Try it

  • Code Diff

    Compare test files when updating component behavior.

  • JSON Formatter

    Format mock API response data used in your tests.

Common mistakes

The mistake

Testing implementation details instead of user behavior

The fix

Do not test component state, internal methods, or exact render counts. Test what the user sees and does: query by role, fire user events, assert on visible output. This makes tests survive refactoring.

The mistake

Using fireEvent instead of userEvent for interactions

The fix

userEvent simulates the full interaction (focus, typing, blur) and waits for updates. fireEvent is lower-level and can miss state updates. Prefer userEvent.setup() and await user.click/type.

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors