Skip to content

Project Tests

The Course
•
20 min study

In React Beginner you tested a small app. The Study Board has a reducer, a context and a custom hook, and each needs a slightly different kind of test. This lesson runs on your own computer.

1. Download and set up

Press Download project under the Study Board lab in the first lesson. Unzip it, open a terminal in the study-board folder, and check you have Node.js 22.12 or later with node --version. Then:

Shell
npm install
Shell
npm install --save-dev vitest jsdom @testing-library/react @testing-library/dom @testing-library/user-event
Shell
npm pkg set scripts.test="vitest"

Add a test section to vite.config.js, as in React Beginner:

JavaScript
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  test: {
    environment: "jsdom",
    globals: true,
  },
});

2. The reducer: plain function tests

Create src/state/boardReducer.test.js:

JavaScript
import { describe, expect, test } from "vitest";
import { boardReducer } from "./boardReducer.js";

const cards = [
  { id: 1, title: "Read", column: "todo", minutes: 20 },
  { id: 2, title: "Build", column: "doing", minutes: 30 },
];

describe("boardReducer", () => {
  test("card_added adds an unfinished card to To do", () => {
    const next = boardReducer(cards, { type: "card_added", id: 3, title: "Test", minutes: 15 });
    expect(next.at(-1)).toEqual({ id: 3, title: "Test", column: "todo", minutes: 15 });
    expect(cards).toHaveLength(2);
  });

  test("card_moved and card_renamed change only the matching card", () => {
    const moved = boardReducer(cards, { type: "card_moved", id: 1, column: "done" });
    expect(moved.map((card) => card.column)).toEqual(["done", "doing"]);
    const renamed = boardReducer(cards, { type: "card_renamed", id: 2, title: "Ship" });
    expect(renamed.map((card) => card.title)).toEqual(["Read", "Ship"]);
  });

  test("card_removed removes by id", () => {
    expect(boardReducer(cards, { type: "card_removed", id: 1 })).toEqual([cards[1]]);
  });

  test("an unknown action throws", () => {
    expect(() => boardReducer(cards, { type: "card_flipped" })).toThrow("Unknown action: card_flipped");
  });
});

These are the Day 2 tests in Vitest form. describe groups related tests, and toThrow checks an error message without a try/catch.

3. The app: tests through the screen

Create src/App.test.jsx:

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 card shows it in To do and updates the stats", async () => {
  const user = userEvent.setup();
  render(<App />);

  await user.type(screen.getByLabelText("Title"), "Write tests");
  await user.click(screen.getByRole("button", { name: "Add card" }));

  expect(screen.getByRole("button", { name: "Write tests" })).toBeTruthy();
  expect(screen.getByRole("heading", { name: "To do (3)" })).toBeTruthy();
  expect(screen.getByText("1 of 5 done · 75 min left")).toBeTruthy();
  expect(document.activeElement).toBe(screen.getByLabelText("Title"));
});

test("a blank title shows an error and focuses the field", async () => {
  const user = userEvent.setup();
  render(<App />);

  await user.click(screen.getByRole("button", { name: "Add card" }));

  expect(screen.getByText("Enter a title.")).toBeTruthy();
  expect(document.activeElement).toBe(screen.getByLabelText("Title"));
});

test("moving a card updates both columns", async () => {
  const user = userEvent.setup();
  render(<App />);

  await user.click(screen.getByRole("button", { name: "Move Read about reducers to Doing" }));

  expect(screen.getByRole("heading", { name: "To do (1)" })).toBeTruthy();
  expect(screen.getByRole("heading", { name: "Doing (2)" })).toBeTruthy();
});

The tests use the app as a person would: by labels, button names and headings. Two details:

  • Headings by role. A column heading's text is split across two elements, To do and (3), so getByText("To do (3)") can't find it. getByRole("heading", { name: "To do (3)" }) matches the heading's accessible name, which joins them, the same name a screen reader announces.
  • Focus is checked too. document.activeElement is the focused element, so the Day 4 focus behaviour is tested, not just eyeballed.

App includes its own BoardProvider, so these tests need no setup.

4. A custom hook: render it inside a provider

Hooks can only run inside components. To test useBoardStats, render a tiny component that calls it, inside a BoardProvider with cards chosen for the test. Create src/hooks/useBoardStats.test.jsx:

JSX
import { render, screen } from "@testing-library/react";
import { expect, test } from "vitest";
import { BoardProvider } from "../state/BoardContext.jsx";
import { useBoardStats } from "./useBoardStats.js";

function Stats() {
  const { total, done, minutesLeft } = useBoardStats();
  return <p>{total} {done} {minutesLeft}</p>;
}

test("useBoardStats counts from the provider's cards", () => {
  const cards = [
    { id: 1, title: "A", column: "done", minutes: 10 },
    { id: 2, title: "B", column: "todo", minutes: 25 },
  ];
  render(
    <BoardProvider initialCards={cards}>
      <Stats />
    </BoardProvider>
  );
  expect(screen.getByText("2 1 25")).toBeTruthy();
});

test("useBoardStats outside a provider names the mistake", () => {
  expect(() => render(<Stats />)).toThrow("useCards must be used inside <BoardProvider>.");
});

This is where initialCards pays off: the test controls exactly which cards the hook sees. The second test checks the Day 3 error message.

5. Run them

Shell
npm test

All 9 tests pass. While Vitest is watching, break something on purpose: remove the return from the card_removed case, or the titleRef.current.focus() after adding a card, and watch which tests fail. Then put it back. Press q to stop.

Exercise

Test renaming

Add a test to App.test.jsx: select Try context, type Use context into the Rename box, press Rename, and check that the card's button now says Use context.

Hint 1: the idea

The Rename box starts with the card's title. Clear it first with await user.clear(screen.getByLabelText("Rename")), then user.type.

Hint 2: a first step

After renaming, both the card and the details panel's heading show Use context. Look for the button: getByRole("button", { name: "Use context" }).

Show one solution
JSX
test("renaming a card from the details panel", async () => {
  const user = userEvent.setup();
  render(<App />);

  await user.click(screen.getByRole("button", { name: "Try context" }));
  await user.clear(screen.getByLabelText("Rename"));
  await user.type(screen.getByLabelText("Rename"), "Use context");
  await user.click(screen.getByRole("button", { name: "Rename" }));

  expect(screen.getByRole("button", { name: "Use context" })).toBeTruthy();
});

Was this article helpful?

Your response is saved on this device.