Sub topic 16
Testing the app with React Testing Library
This chapter adds a first automated test to the to-do app. It assumes you have a Vite React project with the working App component from the earlier chapters. It also assumes you know basic async/await. The examples use Vitest as the test runner. Jest works the same way once the DOM environment is set up.
What React Testing Library tests
React Testing Library (RTL) renders your component into a simulated browser DOM and lets you interact with it the way a user would. It does not look at state or props. It looks at what is on the screen. A test written this way keeps passing when you refactor useState into useReducer, because the visible behavior does not change.
This also explains why the accessibility chapter matters for testing. RTL finds elements by label and role, so a properly labeled input is easy to test, and an unlabeled one is hard to test.
Set up the tools
Install the libraries as development dependencies:
npm install -D vitest jsdom @testing-library/react @testing-library/user-eventThen tell Vitest to use a simulated browser (jsdom) and to provide test and expect globally:
// vite.config.js
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
globals: true,
},
});Add "test": "vitest" to the scripts section of package.json, then run npm test.
Write the first test
Create src/App.test.jsx. A good test follows three steps: arrange (render), act (type and click), assert (check the screen).
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import App from "./App";
test("adds a to-do", async () => {
const user = userEvent.setup();
render(<App />);
await user.type(screen.getByLabelText(/new task/i), "Buy milk");
await user.click(screen.getByRole("button", { name: /add/i }));
expect(screen.getByText("Buy milk")).toBeTruthy();
});Each part has a job:
rendermountsAppinto jsdom.getByLabelTextfinds the input through its<label>, which is how a screen reader user finds it.getByRolefinds the button by its role and visible name.userEventfires the full sequence of real events, such as focus, key presses, and input changes. Alwaysawaitits methods.getByTextthrows an error if nothing matches, so a missing item fails the test even beforeexpectruns.
Test toggling
A second test checks behavior that depends on state changing after the first action:
test("marks a to-do as done", async () => {
const user = userEvent.setup();
render(<App />);
await user.type(screen.getByLabelText(/new task/i), "Buy milk");
await user.click(screen.getByRole("button", { name: /add/i }));
const checkbox = screen.getByRole("checkbox", { name: /buy milk/i });
expect(checkbox.checked).toBe(false);
await user.click(checkbox);
expect(checkbox.checked).toBe(true);
});Common errors
- Forgetting
await. The assertion runs before the click is processed, so the test fails at random. - Unable to find an element. The error output prints the current DOM and lists the roles that are available. Check the label text and the role first.
- Leaking state between tests. If you added localStorage persistence, saved to-dos from one test appear in the next. Call
localStorage.clear()inside abeforeEachblock. - Querying by CSS class or test ID first. Prefer
getByRoleandgetByLabelText. UsegetByTestIdonly when nothing user-facing identifies the element. - Using
getByfor absence. UsequeryByText, which returnsnullinstead of throwing, when you expect something not to be there.
Exercise
Write a test that adds "Buy milk", clicks its Delete button, and checks that the item is gone. Which query should you use for the final assertion, and why?
Show answer
Click the button with await user.click(screen.getByRole("button", { name: /delete/i })). For the assertion use expect(screen.queryByText("Buy milk")).toBeNull(). queryByText returns null when nothing matches, while getByText would throw an error and fail the test even though the item being missing is the result you want.