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.

In shortTest what the user sees and does: render, click, type, then assert on the screen.

Theory in plain words

A component testrender(<Counter />)user clicksthe buttonscreen findsthe textexpect(...)assertion
A component test

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
Install and configure
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";
A test
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();
});

Quick quiz

1. Which tool provides a fake browser DOM?

2. Preferred query in Testing Library?

3. findBy queries are for...

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.