Testing React Components
Render, query, and assert on components with Testing Library and Vitest.
What you'll learn
- Rendering components into a jsdom environment with render
- Querying by role and text instead of implementation details
- Firing user events and awaiting async UI updates
- Asserting accessibility and visible behavior, not internals
Concept
Testing Library Philosophy
React Testing Library (with @testing-library/react and @testing-library/user-event) renders your component into a fake DOM and lets you query and interact with it the way a real user would — by visible text, roles, and labels. Its guiding principle is "the more your tests resemble the way your software is used, the more confidence they give you." It deliberately avoids exposing component internals, steering you toward testing behavior.
Setup
Configure Vitest with environment: 'jsdom' (or 'happy-dom') so document exists. Install @testing-library/react, @testing-library/jest-dom (for matchers like toBeInTheDocument), and @testing-library/user-event for realistic events. Add setupFiles that imports @testing-library/jest-dom/vitest to register the matchers.
Queries and Events
Prefer getByRole and getByLabelText over getByTestId — role-based queries also enforce accessibility (a button with no accessible name fails the query). Use userEvent.click and userEvent.type rather than fireEvent, because userEvent simulates the full user interaction sequence (focus, key presses, change events). For async UI, findBy queries wait for elements to appear, and waitFor wraps assertions that settle after a tick.
What to Assert
Assert on what the user sees: visible text, presence of an error message, that a link points to the right URL. Avoid asserting on internal state, component instance methods, or CSS class names that are implementation details. When a component's behavior changes but its visible output does not, your tests should not need to change.
In Practice
A healthy component test suite renders each component in a few representative states (default, loading, error, empty) and asserts on the visible output and the user interactions. Mock the data-fetching layer at the boundary so tests stay fast and do not hit the network, but let the component's own rendering and event handling run for real. Use findBy queries for elements that appear after an async update, and waitFor to assert on state that settles after a tick. Avoid snapshot tests for components unless the output is stable and someone will review the diffs — behavior assertions are more meaningful. When a test breaks because you renamed a CSS class, the test was too coupled to implementation; rewrite it to query by role or visible text so it survives styling refactors.
Example
import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { Counter } from "./Counter";
describe("Counter", () => {
it("increments when the button is clicked", async () => {
const user = userEvent.setup();
render(<Counter />);
const button = screen.getByRole("button", { name: /increment/i });
expect(screen.getByText("Count: 0")).toBeInTheDocument();
await user.click(button);
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});
});
The test renders Counter, finds the button by its accessible name, clicks it via userEvent, and asserts the visible text updates. No internals are touched.
Try it
- JSON Formatter
Inspect the props and state you pass into components.
- Code Diff
Compare rendered output snapshots when components change.
Common mistakes
The mistake
Querying by CSS class or testid instead of role
The fix
Prefer getByRole and getByLabelText. They test accessibility too — a component that is not queryable by role is not usable by screen readers.
The mistake
Using fireEvent instead of userEvent for interactions
The fix
userEvent simulates the real user sequence (focus, keydown, input, keyup). fireEvent dispatches a single synthetic event and misses real-world side effects.
Practice Testing React Components
6 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.