Skip to content

What to Test

The Course
•
15 min study

Tests that let you change code

You've written tests in both earlier courses. Today is about which tests to write. A good test suite does two things: it fails when the app breaks, and it keeps passing while you restructure code that still works. A test that fails after a harmless refactor is a cost, not a safety net.

The rule that gets you both: test what users and other code can observe, not how it's done inside.

Four levels

LevelWhat it checksExample from today
A plain functionInputs to outputs, no ReactA reducer, a selector, a formatter
A hookWhat a hook returns as its inputs changeuseDebouncedValue, useTopicSearch
A componentWhat a person sees and doesTopicSearch: type, see results
The appSeveral parts working togetherThe whole page in a browser

Lower levels are fast and pinpoint the problem; higher levels catch the bugs that live between parts. Most of your tests should be component tests that use the screen like a person, plus focused tests for logic that's tricky on its own, like timing and races.

The Topic Finder

Today's app searches a pretend server as you type. It waits until you stop typing for 300 ms, then the server answers 400 ms later. A search with an ! in it fails, so you can see the error state.

The Topic Finder React · 8 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { topics } from "./topics.js"; // A pretend server. It answers after 400 ms, and fails for any search with // an exclamation mark in it, so you can see the error state. export function searchTopics(query) { return new Promise((resolve, reject) => { setTimeout(() => { if (query.includes("!")) reject(new Error("The server is having a bad day.")); else resolve(topics.filter((t) => t.toLowerCase().includes(query.trim().toLowerCase()))); }, 400); }); } import TopicSearch from "./TopicSearch.jsx"; export default function App() { return ( <main> <h1>Topic Finder</h1> <TopicSearch /> </main> ); } export const topics = [ "Compound components", "Controlled props", "Render props", "Imperative handles", "External stores", "Selectors", "State machines", "Suspense", "Request cache", "Lazy loading", "Profiling", "Windowing", "Activity", "Dialogs", "Comboboxes", ]; import { useState } from "react"; import { useTopicSearch } from "./useTopicSearch.js"; export default function TopicSearch() { const [query, setQuery] = useState(""); const { status, results, error, retry } = useTopicSearch(query); return ( <section> <label> Search topics <input value={query} onChange={(e) => setQuery(e.target.value)} /> </label> <p className="muted" role="status"> {status === "loading" && "Searching…"} {status === "done" && `${results.length} ${results.length === 1 ? "result" : "results"}`} </p> {status === "error" && ( <div role="alert"> {error.message} <button onClick={retry}>Try again</button> </div> )} <ul className="cards"> {results.map((t) => <li key={t} className="card">{t}</li>)} </ul> </section> ); } import { useEffect, useState } from "react"; // Returns value, but only once it has stopped changing for `delay` ms. export function useDebouncedValue(value, delay) { const [debounced, setDebounced] = useState(value); useEffect(() => { const id = setTimeout(() => setDebounced(value), delay); return () => clearTimeout(id); }, [value, delay]); return debounced; } import { useEffect, useState } from "react"; import { searchTopics } from "./api.js"; import { useDebouncedValue } from "./useDebouncedValue.js"; // Searches once typing pauses. Answers to older searches are ignored, so a // slow early answer can't replace a newer one. export function useTopicSearch(query) { const debounced = useDebouncedValue(query, 300); const [attempt, setAttempt] = useState(0); const [state, setState] = useState({ status: "idle", results: [], error: null }); useEffect(() => { if (debounced.trim() === "") { setState({ status: "idle", results: [], error: null }); return; } let ignore = false; setState((s) => ({ ...s, status: "loading", error: null })); searchTopics(debounced).then( (results) => { if (!ignore) setState({ status: "done", results, error: null }); }, (error) => { if (!ignore) setState({ status: "error", results: [], error }); }, ); return () => { ignore = true; }; }, [debounced, attempt]); return { ...state, retry: () => setAttempt((a) => a + 1) }; } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Type sel, then sel!, then press Try again.

There's a lot to get right in useTopicSearch: the debounce, the loading and error states, retrying, and ignoring a slow answer to an old search. Each of those deserves a test:

JavaScript
export function useTopicSearch(query) {
  const debounced = useDebouncedValue(query, 300);
  const [attempt, setAttempt] = useState(0);
  const [state, setState] = useState({ status: "idle", results: [], error: null });

  useEffect(() => {
    if (debounced.trim() === "") {
      setState({ status: "idle", results: [], error: null });
      return;
    }
    let ignore = false;
    setState((s) => ({ ...s, status: "loading", error: null }));
    searchTopics(debounced).then(
      (results) => { if (!ignore) setState({ status: "done", results, error: null }); },
      (error) => { if (!ignore) setState({ status: "error", results: [], error }); },
    );
    return () => { ignore = true; };
  }, [debounced, attempt]);

  return { ...state, retry: () => setAttempt((a) => a + 1) };
}

Set up the project

The rest of today runs on your own computer. Press Download project under the lab, unzip it, and open a terminal in the topic-finder folder. You need Node.js 22.12 or later. 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"

In vite.config.js, add the test section:

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

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

npm test now runs Vitest in watch mode: it reruns the tests as you save.

Exercise

Sort the tests

For each test, pick the level it belongs at, and say whether it would survive renaming status to phase inside useTopicSearch.

  1. "Typing sel shows 1 result."
  2. "After a search, the hook's state object is { status: "done", ... }."
  3. "The Try again button is inside an element with role="alert"."
  4. "A slow answer to an old search never replaces a newer one."
Hint 1: the idea

A test should depend on the contract of the thing it tests. Internal names and public return fields are different contracts.

Hint 2: a first step

Ask what each test reads: the screen, or the hook's return value? And is the name status part of what it checks?

Show one solution
  1. Component. It survives: it reads only the screen.
  2. Hook. It breaks: status is the hook's public return value, so renaming it is a real API change, and this test should fail. That's fine, as long as tests don't reach into names that are private.
  3. Component. It survives, and it checks something users rely on: screen readers announce the alert.
  4. Hook, because the timing is easiest to control there. It survives as long as it checks results, not status.

Was this article helpful?

Your response is saved on this device.