Skip to content

Project Tests

The Course
•
20 min study

This lesson runs on your own computer. Press Download project under the Study Hub lab in the first lesson, set it up as on Day 6, and run npm test as you add each file.

1. A stand-in for showModal

jsdom, the pretend browser Vitest uses, has no showModal() or close() on <dialog>. Any test that opens the palette fails with dialog.showModal is not a function. Create src/test/setup.js:

JavaScript
// jsdom has no showModal() or close(). This stand-in opens and closes the
// dialog and fires "close", which is enough for these tests. It doesn't move
// focus, block the page or handle Escape: check those in a real browser.
HTMLDialogElement.prototype.showModal = function () {
  this.setAttribute("open", "");
};

HTMLDialogElement.prototype.close = function () {
  if (!this.hasAttribute("open")) return;
  this.removeAttribute("open");
  this.dispatchEvent(new Event("close"));
};

and load it before every test file in vite.config.js:

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

export default defineConfig({
  plugins: [react()],
  test: {
    environment: "jsdom",
    globals: true,
    setupFiles: ["./src/test/setup.js"],
  },
});

Notice what the stand-in doesn't do. Moving focus in, blocking the page and Escape are exactly the things that make the native dialog worth using, and jsdom can't check them. Check those in a real browser: by hand, or with a browser test runner such as Vitest's browser mode or Playwright.

2. The stores: plain tests

The stores are plain JavaScript, so they're the quickest to test. src/store/timer.test.js:

JavaScript
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { FOCUS_SECONDS, send, timer } from "./timer.js";

beforeEach(() => {
  vi.useFakeTimers();
});

afterEach(() => {
  send("RESET");
  vi.useRealTimers();
});

test("START counts down once a second", () => {
  send("START");
  vi.advanceTimersByTime(3000);
  expect(timer.getState()).toMatchObject({ status: "focusing", remaining: FOCUS_SECONDS - 3 });
});

test("PAUSE stops the clock, and RESUME carries on", () => {
  send("START");
  vi.advanceTimersByTime(2000);
  send("PAUSE");
  vi.advanceTimersByTime(5000);
  expect(timer.getState().remaining).toBe(FOCUS_SECONDS - 2);

  send("RESUME");
  vi.advanceTimersByTime(1000);
  expect(timer.getState().remaining).toBe(FOCUS_SECONDS - 3);
});

test("reaching zero starts a break and counts a session", () => {
  const before = timer.getState().sessions;
  send("START");
  vi.advanceTimersByTime(FOCUS_SECONDS * 1000);
  expect(timer.getState()).toMatchObject({ status: "onBreak", sessions: before + 1 });
});

test("events a state doesn't accept change nothing", () => {
  const state = timer.getState();
  send("PAUSE");
  expect(timer.getState()).toBe(state);
});

The ticker starts with send("START"), inside the test, so the fake clock controls it. The store is shared by every test in the file, so afterEach sends RESET to put it back.

src/store/progress.test.js:

JavaScript
import { beforeEach, expect, test } from "vitest";
import { doneCount, isDone, progress, resetProgress, toggleDone } from "./progress.js";

beforeEach(() => {
  resetProgress();
});

test("toggleDone marks a topic done, then not done", () => {
  toggleDone(3);
  expect(isDone(3)(progress.getState())).toBe(true);
  toggleDone(3);
  expect(isDone(3)(progress.getState())).toBe(false);
});

test("subscribers hear about each change", () => {
  const heard = [];
  const unsubscribe = progress.subscribe(() => heard.push(doneCount(progress.getState())));
  toggleDone(1);
  toggleDone(2);
  unsubscribe();
  toggleDone(3);
  expect(heard).toEqual([1, 2]);
});

The second test checks the store's contract with React: subscribers are told about each change. A store that changed its state in place would fail it, and React would never re-render.

3. A screen that suspends

src/topics/TopicsPanel.test.jsx:

JSX
import { act, fireEvent, render, screen } from "@testing-library/react";
import { beforeEach, expect, test, vi } from "vitest";
import { fetchTopic } from "../data/api.js";
import { topics } from "../data/topics.js";
import TopicsPanel from "./TopicsPanel.jsx";

vi.mock("../data/api.js", () => ({ fetchTopic: vi.fn() }));

beforeEach(() => {
  fetchTopic.mockImplementation(async (id) => ({ ...topics.find((t) => t.id === id), summary: `About ${id}` }));
});

// Anything that can suspend goes inside an awaited act(), so React finishes
// loading before the next line.
async function setup() {
  await act(async () => render(<TopicsPanel />));
  const click = (name) => act(async () => fireEvent.click(screen.getByRole("button", { name })));
  return { click };
}

test("shows the first topic, then the one you choose", async () => {
  const { click } = await setup();
  expect(screen.getByRole("heading", { name: "Compound components" })).toBeTruthy();

  await click("Dialogs");

  expect(screen.getByRole("heading", { name: "Dialogs" })).toBeTruthy();
  expect(screen.getByText("About 9")).toBeTruthy();
  expect(fetchTopic).toHaveBeenLastCalledWith(9);
});

test("a failed topic shows an alert, and Try again loads it", async () => {
  fetchTopic.mockRejectedValueOnce(new Error("Offline"));
  const { click } = await setup();

  await click("Windowing");
  expect(screen.getByRole("alert").textContent).toContain("Offline");

  await click("Try again");
  expect(screen.getByRole("heading", { name: "Windowing" })).toBeTruthy();
});

Awaited act around anything that suspends. TopicsPanel suspends while a topic loads, and selecting a topic suspends inside a transition. React only finishes that work promptly in a test when it happens inside an await act(...). Try it: change setup() to a plain render(<TopicsPanel />) and click with userEvent. The tests fail because the details never finish loading, and React warns A component suspended inside an act scope, but the act call was not awaited. Awaiting act waits for the mocked server and the re-render, so each check can use getBy right away.

Inside act, the clicks use fireEvent rather than userEvent: userEvent manages act itself, and nesting it inside another act triggers warnings.

The error test prints Error: Offline to the console. That's React reporting the error the boundary caught, not a failure.

4. The palette, through the whole app

src/App.test.jsx:

JSX
import { act, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test, vi } from "vitest";
import App from "./App.jsx";

vi.mock("./data/api.js", () => ({
  fetchTopic: vi.fn(async (id) => ({ id, title: `Topic ${id}`, day: 1, summary: "" })),
}));

test("Ctrl+K opens the palette, and a command switches tabs", async () => {
  const user = userEvent.setup();
  await act(async () => render(<App />));

  await user.keyboard("{Control>}k{/Control}");
  // The stand-in showModal() doesn't move focus, so type into the box directly.
  const input = screen.getByRole("combobox", { name: "Command" });

  await user.type(input, "stats");
  await user.keyboard("{ArrowDown}{Enter}");

  expect(screen.getByRole("status").textContent).toBe("Ran: Go to Stats");
  expect(screen.getByRole("tab", { name: "Stats" }).getAttribute("aria-selected")).toBe("true");
  expect(await screen.findByRole("heading", { name: "0 of 12 topics done" }, { timeout: 2000 })).toBeTruthy();
});
  • {Control>}k{/Control} holds Control while pressing K.
  • The server is mocked here too, so topic 1 loads instantly and the test doesn't depend on its 500 ms delay.
  • Stats is lazy-loaded with a 600 ms wait, so its heading needs a findBy with a longer timeout.

Run them all

Shell
npm test

Nine tests in four files. Then break something on purpose: in store/progress.js, make toggleDone push onto state.done and return the same state. Which test fails?

Check

subscribers hear about each change. The store's setState sees the same object, decides nothing changed, and tells no one. In the app, the checkbox wouldn't tick. Put the original back.

Was this article helpful?

Your response is saved on this device.