Sub topic 16
Testing the app with React Testing Library
This chapter assumes you have the to-do app from the earlier chapters: an App component with a controlled "New task" input, an "Add" button, and a list of items. It also assumes you can read basic async/await code and have used npm. You will write tests that check what a user sees and does, not how the component is built inside.
Why test behavior, not implementation
A test that reads useState values or checks component internals breaks whenever you refactor. You moved state into a reducer in an earlier chapter, and a good test should survive that change without edits.
React Testing Library (RTL) is built around that idea. It renders your component into a DOM, then gives you queries that find elements the way a user or a screen reader would: by label, by role, by visible text. If a test cannot find an element this way, the app is often hard for real users to use too. That links this chapter to the accessibility chapter.
Setting up the tools
RTL does not run tests by itself. You need a test runner and a DOM environment. With a Vite project, Vitest is the natural choice.
npm install -D vitest jsdom @testing-library/react @testing-library/user-event @testing-library/jest-domThen configure Vitest in vite.config.js:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
globals: true,
setupFiles: "./src/setupTests.js",
},
});jsdom is a JavaScript implementation of the browser DOM that runs in Node. globals: true makes test, expect, and afterEach available without imports. The setup file registers extra matchers and cleans up after each test:
import "@testing-library/jest-dom/vitest";With globals: true, RTL registers automatic cleanup after each test, so rendered components are removed from the DOM between tests. Without globals, you must call cleanup() yourself in an afterEach.
Add a script to package.json:
{
"scripts": {
"test": "vitest"
}
}Run npm test and Vitest watches your files and re-runs affected tests as you save.
The render, act, assert cycle
Every RTL test follows the same three steps.
- Render the component with
render. - Act the way a user would: type, click, tab.
- Assert on what is now on screen.
Here is the test from the topic outline, which adds a to-do:
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();
});Some points about it:
userEvent.setup()creates a user session. Call it beforerender. Its methods return promises, so youawaiteach one.getByLabelText(/new task/i)finds the input through its<label>. If you had skipped the label in the accessibility chapter, this query would fail. That failure is the test doing its job.- A regular expression with the
iflag matches case-insensitively, so small copy changes such as "New Task" do not break the test. toBeTruthy()works with no extra setup. Withjest-domregistered,toBeInTheDocument()gives clearer failure messages.
Choosing the right query
Queries come in three families, and the prefix tells you what happens when nothing matches.
| Prefix | No match | Multiple matches | Use it for |
|---|---|---|---|
| `getBy` | Throws | Throws | Elements that must be present now |
| `queryBy` | Returns `null` | Throws | Asserting that something is absent |
| `findBy` | Rejects after a timeout | Rejects | Elements that appear asynchronously |
Each family has AllBy versions (getAllByRole) that return arrays.
The suffix says how to find the element. Prefer them in this order:
ByRole, with thenameoption. It matches the accessibility tree, sogetByRole("button", { name: /delete/i })checks that the element is a real button with an accessible name.ByLabelTextfor form fields.ByTextfor non-interactive content.ByTestIdonly when nothing else works, because users cannot see adata-testid.
Testing toggle and delete
Add two more tests. Start each from a known state by adding an item through the UI, as a user would. A small helper keeps the tests short:
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import App from "./App";
async function addTodo(user, title) {
await user.type(screen.getByLabelText(/new task/i), title);
await user.click(screen.getByRole("button", { name: /add/i }));
}
test("clears the input after adding", async () => {
const user = userEvent.setup();
render(<App />);
await addTodo(user, "Buy milk");
expect(screen.getByLabelText(/new task/i)).toHaveValue("");
});
test("toggles a to-do as done", async () => {
const user = userEvent.setup();
render(<App />);
await addTodo(user, "Buy milk");
const checkbox = screen.getByRole("checkbox", { name: /buy milk/i });
expect(checkbox).not.toBeChecked();
await user.click(checkbox);
expect(checkbox).toBeChecked();
});
test("deletes a to-do", async () => {
const user = userEvent.setup();
render(<App />);
await addTodo(user, "Buy milk");
await user.click(screen.getByRole("button", { name: /delete/i }));
expect(screen.queryByText("Buy milk")).not.toBeInTheDocument();
});These tests use toHaveValue, toBeChecked, and toBeInTheDocument, which come from jest-dom. They work only because of the setup file above. The toggle test relies on the TodoItem from earlier, where the checkbox sits inside a <label> that contains the title. That wrapping is what gives the checkbox its accessible name.
The delete test uses queryBy, not getBy. getBy would throw as soon as the element was missing, so you could never assert absence with it.
Testing the filter
The filter chapter derived visibleTodos and remaining during render. You can test that behavior without knowing how it is computed. This test assumes your filter controls are buttons named "All", "Active", and "Completed", and that the app shows the remaining count as text such as "1 item left". Adjust the names to match your own markup.
test("filters completed items", async () => {
const user = userEvent.setup();
render(<App />);
await addTodo(user, "Buy milk");
await addTodo(user, "Walk dog");
await user.click(screen.getByRole("checkbox", { name: /buy milk/i }));
await user.click(screen.getByRole("button", { name: /^active$/i }));
expect(screen.queryByText("Buy milk")).not.toBeInTheDocument();
expect(screen.getByText("Walk dog")).toBeInTheDocument();
expect(screen.getByText(/1 item left/i)).toBeInTheDocument();
});The ^ and $ anchors in /^active$/i stop the pattern from also matching a button called "Inactive" or "Show active items". Overly loose patterns are a common cause of "found multiple elements" errors.
Testing persistence
The usePersistentState hook reads and writes localStorage. jsdom provides a working localStorage, but it lives across tests in the same file. Clear it so one test cannot leak data into the next:
beforeEach(() => {
localStorage.clear();
});
test("restores saved to-dos on load", () => {
localStorage.setItem(
"todos",
JSON.stringify([{ id: "1", title: "Saved task", done: false }])
);
render(<App />);
expect(screen.getByText("Saved task")).toBeInTheDocument();
});The storage key "todos" must match what your app passes to usePersistentState. Because the hook reads storage in a lazy initializer, the data must be in place before render. Setting it afterward has no effect.
Common errors
- "Unable to find a label with the text of...": the input has no associated
<label>, or the text differs. Check the markup first, then the regular expression. - "Found multiple elements": the query is too loose, or earlier tests left DOM behind. Make the pattern stricter, or confirm that cleanup runs.
- "not wrapped in act(...)" warnings: you forgot to
awaitauserEventcall, so a state update happened outside the test's flow. Await everyuser.*call. document is not defined: the test environment isnode. Setenvironment: "jsdom".toBeInTheDocument is not a function: thejest-domimport is missing from the setup file.- A test passes alone but fails with others: shared state, usually
localStorage. Reset it inbeforeEach.
What to test and what to skip
Test behavior a user depends on: adding, toggling, deleting, filtering, and persistence. Skip the details of React itself, such as whether setTodos was called. Avoid snapshot tests of the whole app, since they fail on any markup change and teach you little.
Because the tests only use the screen, you can move the logic into useReducer, add context, or restructure components, and the same tests still verify the app.
Exercise
In the delete test, why does the final assertion use queryByText together with .not.toBeInTheDocument() instead of getByText?
Show answer
getByText throws an error when no element matches, so the test would fail with an exception at the moment the item is correctly gone. queryByText returns null when nothing matches, which lets .not.toBeInTheDocument() check that the item is absent.
Exercise
Write a test that checks that submitting the form with only spaces in the input does not add an item. Assume the list is a <ul> that exposes the list role, and use queryByRole for the check.
Show answer
test("ignores blank titles", async () => {
const user = userEvent.setup();
render(<App />);
await user.type(screen.getByLabelText(/new task/i), " ");
await user.click(screen.getByRole("button", { name: /add/i }));
expect(screen.queryAllByRole("listitem")).toHaveLength(0);
});
The addTodo handler trims the text and returns early when it is empty, so no <li> is rendered. queryAllByRole returns an empty array when nothing matches, so the length check works. Note that queryByRole("list") can still find an empty <ul>, so checking list items is the more reliable assertion.