AI Hints
Home›React Tutorial›Testing and Shipping
React · Lesson 82 of 120

Testing Components

What to test.

⏱ 2 min read▶ Video at 1:09:43🎓 Free
Watch this lesson in the React courseWatch on YouTube ↗Full React course

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.

keyvalue
Testwhat users see
Notinternal state
Easiestreducers, pure functions
Runnpx 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