Home / Learn React / Testing React Components
Testing React Components
Tests check that your components work, so you can change code without fear. Vitest and React Testing Library are the common choice with Vite.
Theory in plain words
What it is
A component test renders a component in a fake DOM, interacts like a user and checks the result. Testing Library encourages queries by role and text, not by internal details.
Why we use it
Tests catch regressions, document behaviour and let you refactor safely.
How it works
Vitest runs the test, jsdom provides a browser-like DOM, Testing Library renders and queries, user-event simulates real typing and clicks.
Where it is used
- Every serious project, especially forms, calculations and critical flows
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-dom
// vite.config.js
test: { environment: "jsdom", setupFiles: "./src/setup.js", globals: true }
// src/setup.js
import "@testing-library/jest-dom/vitest";import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import Counter from "./Counter";
test("increments on click", async () => {
render(<Counter />);
await userEvent.click(screen.getByRole("button", { name: /add/i }));
expect(screen.getByText("Count: 1")).toBeInTheDocument();
});- Prefer
getByRoleandgetByLabelText: they also check accessibility. - Use
findBy...for things that appear later andqueryBy...to assert that something is absent. - Do not test React itself or implementation details such as internal state names.
Quick quiz
1. Which tool provides a fake browser DOM?
jsdom.
2. Preferred query in Testing Library?
It mirrors how users and assistive tech find things.
3. findBy queries are for...
They wait for elements to appear.
Common questions
Which tool provides a fake browser DOM?
jsdom. jsdom.
Preferred query in Testing Library?
getByRole. It mirrors how users and assistive tech find things.