Clicking through the app after every change gets slow, and it's easy to miss something. Automated tests click through for you, in a second, every time. You'll use Vitest, a test runner made for Vite projects, and React Testing Library, which renders components and uses them the way a person would.
Work in the Study Tasks project from the last lesson, with storage added.
1. Install and configure
In the project folder (stop npm run dev with Ctrl + C first, or use a
second terminal):
npm install --save-dev vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-eventnpm pkg set scripts.test="vitest"Then add a test section to vite.config.js:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
globals: true,
},
});environment: "jsdom"gives tests a pretend browser page, with adocumentandlocalStorage, inside Node.globals: truelets React Testing Library clean up between tests on its own. Without it, each test's page stays on screen for the next one, and you'd see errors such as Found multiple elements with the role "button".
2. Test the pure functions
Create src/tasks.test.js:
import { expect, test } from "vitest";
import { addTask, removeTask, summary, toggleTask, visibleTasks } from "./tasks.js";
const tasks = [
{ id: 1, title: "Read", minutes: 20, done: true },
{ id: 2, title: "Build", minutes: 30, done: false },
];
test("addTask adds an unfinished task and leaves the old array alone", () => {
const result = addTask(tasks, "Test", 15);
expect(result).toHaveLength(3);
expect(result[2]).toMatchObject({ title: "Test", minutes: 15, done: false });
expect(tasks).toHaveLength(2);
});
test("toggleTask flips only the matching task", () => {
const result = toggleTask(tasks, 2);
expect(result.map((task) => task.done)).toEqual([true, true]);
expect(tasks[1].done).toBe(false);
});
test("removeTask removes by id", () => {
expect(removeTask(tasks, 1).map((task) => task.id)).toEqual([2]);
});
test("visibleTasks filters by status", () => {
expect(visibleTasks(tasks, "active").map((task) => task.title)).toEqual(["Build"]);
expect(visibleTasks(tasks, "done").map((task) => task.title)).toEqual(["Read"]);
expect(visibleTasks(tasks, "all")).toBe(tasks);
});
test("summary counts unfinished tasks and their minutes", () => {
expect(summary(tasks)).toEqual({ left: 1, minutesLeft: 30 });
expect(summary([])).toEqual({ left: 0, minutesLeft: 0 });
});Each test has a name that says what should be true, and expect(...) checks
it. Notice the checks that the old array didn't change: they guard Day 4's
rule.
3. Test the app like a user
Create src/App.test.jsx:
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test } from "vitest";
import App from "./App.jsx";
test("adding a task shows it and updates the summary", async () => {
const user = userEvent.setup();
render(<App />);
await user.type(screen.getByLabelText("Task"), "Learn effects");
await user.click(screen.getByRole("button", { name: "Add" }));
expect(screen.getByText("Learn effects")).toBeTruthy();
expect(screen.getByText("3 left, 70 minutes")).toBeTruthy();
});
test("a blank task name shows an error and adds nothing", async () => {
const user = userEvent.setup();
render(<App />);
await user.click(screen.getByRole("button", { name: "Add" }));
expect(screen.getByText("Give the task a name.")).toBeTruthy();
expect(screen.getByText("2 left, 55 minutes")).toBeTruthy();
});
test("the Done filter shows only finished tasks", async () => {
const user = userEvent.setup();
render(<App />);
await user.click(screen.getByRole("button", { name: "Done" }));
expect(screen.getByText("Read about components")).toBeTruthy();
expect(screen.queryByText("Pass props to a child")).toBeNull();
});The tests find things the way a person does: by label, by a button's name, by
visible text. They don't look at state or class names, so you can rewrite a
component's insides and the tests still pass, as long as it works the same for
the user. getBy... fails if nothing matches; queryBy... returns null
instead, for checking that something is not there.
4. Run them, and read the failure
npm testVitest runs both files and keeps watching. Save any file and it runs again.
One test fails: a blank task name shows an error and adds nothing, because it can't find 2 left, 55 minutes. Before reading on, work out why from the last lesson.
Why it fails
The first test added Learn effects, and the storage effect saved it. The
second test's App loaded that saved list, so it starts with three tasks, not
two. Tests that share state like this pass or fail depending on their order,
which makes them unreliable.
Give each test a clean start. At the top of src/App.test.jsx, import
beforeEach as well, and clear storage before every test:
import { beforeEach, expect, test } from "vitest";// Each test starts with no saved tasks, whatever the last test added.
beforeEach(() => {
localStorage.clear();
});All 8 tests pass. Press q to stop Vitest.
Your turn
Test the removal
Write a test in App.test.jsx that removes Read about components with its
× button, and checks that it's gone and that the summary still says 2
left, 55 minutes.
Hint 1: the idea
The × buttons have aria-labels such as Remove Read about components,
and getByRole uses that as the name.
Hint 2: a first step
queryByText returns null when nothing matches.
Show one solution
test("removing a finished task keeps the summary", async () => {
const user = userEvent.setup();
render(<App />);
await user.click(screen.getByRole("button", { name: "Remove Read about components" }));
expect(screen.queryByText("Read about components")).toBeNull();
expect(screen.getByText("2 left, 55 minutes")).toBeTruthy();
});The summary doesn't change because the removed task was already done. Testing that boundary is worth it: a bug that counted removed tasks would show up here.
Completion is saved in this browser only. It does not measure mastery.