React · Lesson 82 of 120
Testing Components
What to test.
Tests let you change code with confidence. For React, the best tests use the component the way a user would. Find things by their text or role, click them, and check what appears.
- Change with confidence
- Test like a user
- Click and check
A component test
This test uses Vitest, and React Testing Library. It renders the counter. It finds the button by its role and name, and clicks it. Then it checks the new text appears on the screen.
Counter.test.jsxjsx
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { test, expect } from "vitest";
import Counter from "./Counter";
test("adds a helmet when the button is clicked", async () => {
render(<Counter />);
await userEvent.click(screen.getByRole("button", { name: "Add a helmet" }));
expect(screen.getByText("1")).toBeInTheDocument();
});What to test
Test behaviour, not implementation. What the user sees, and what happens when they act. Don't test state variables directly. Pure functions, like reducers, are the easiest of all to test.
| key | value |
|---|---|
| Test | what users see |
| Not | internal state |
| Easiest | reducers, pure functions |
| Run | npx vitest |
Summary
Test components the way users use them, by text and role. Next, building for production.
Key takeaways- Vitest
- Testing Library
- getByRole
Next up: Building for Production — Vite