TopicSearch changes over time: nothing, then Searching…, then results.
A test has to wait for each step without guessing how long it takes:
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>
);
}Waiting with findBy
Create src/TopicSearch.test.jsx:
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { expect, test } from "vitest";
import TopicSearch from "./TopicSearch.jsx";
test("typing shows Searching…, then the results", async () => {
const user = userEvent.setup();
render(<TopicSearch />);
await user.type(screen.getByLabelText("Search topics"), "sel");
expect(await screen.findByText("Searching…")).toBeTruthy();
expect(await screen.findByText("1 result", {}, { timeout: 2000 })).toBeTruthy();
expect(screen.getByRole("listitem").textContent).toBe("Selectors");
});
test("a failed search shows the error as an alert", async () => {
const user = userEvent.setup();
render(<TopicSearch />);
await user.type(screen.getByLabelText("Search topics"), "sel!");
const alert = await screen.findByRole("alert", {}, { timeout: 2000 });
expect(alert.textContent).toContain("The server is having a bad day.");
});findBy…queries keep trying until the element appears, or fail after a timeout. They return a promise, soawaitthem.- The timeout. By default
findBygives up after 1 second. This search takes 700 ms, which is too close, so the test allows 2 seconds as the third argument. getBy…is for something that should already be there; use it once you've waited.
These tests use real time, so together they take nearly 2 seconds. That's acceptable for two tests, but a suite with a hundred like them is slow, and close timeouts can fail on a busy computer.
Fake timers with a real user
Create src/TopicSearch.fake.test.jsx:
import { act, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import TopicSearch from "./TopicSearch.jsx";
beforeEach(() => {
vi.useFakeTimers({ shouldAdvanceTime: true });
});
afterEach(() => {
vi.useRealTimers();
});
test("searches 300 ms after typing stops, and shows results 400 ms later", async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<TopicSearch />);
await user.type(screen.getByLabelText("Search topics"), "sel");
expect(screen.getByRole("status").textContent).toBe("");
await act(() => vi.advanceTimersByTimeAsync(300));
expect(screen.getByRole("status").textContent).toBe("Searching…");
await act(() => vi.advanceTimersByTimeAsync(400));
expect(screen.getByRole("status").textContent).toBe("1 result");
expect(screen.getByRole("listitem").textContent).toBe("Selectors");
});It checks the exact timing, and nothing waits for the real 700 ms. Three details matter, and each one hangs or fails the test if it's missing:
advanceTimers: vi.advanceTimersByTimetellsuserEventto move the fake clock when it waits between keystrokes.shouldAdvanceTime: truekeeps the fake clock ticking slowly with real time too. Testing Library waits on a shortsetTimeoutafter each action, and it only knows how to move Jest's fake clock, not Vitest's. With a completely frozen clock, that timer never fires and the test times out after 5 seconds.- One
actper step. React starts the search in an effect, after the debounced value updates. Inside a singleact, effects run when theactfinishes, so advancing 700 ms at once would run the debounce but not the search. Advance 300 ms, then 400 ms, as the app would experience it.
advanceTimersByTimeAsync is the async version: it also lets promises, such as
the server's answer, settle between timers.
Predict
In the fake-timer test, change the two act calls into one that advances
700 ms. What does the last check see?
Check your prediction
Searching…: the search started at the end of the act, so its 400 ms timer
hasn't run yet. Put the two steps back.
Test Try again
With fake timers, test that Try again searches again: type sel!, wait for the alert, press Try again, then check the alert has gone and the status says Searching…, and that the alert comes back 400 ms later.
Hint 1: the idea
Copy beforeEach, afterEach and the userEvent.setup line from the
fake-timer test.
Hint 2: a first step
getByRole throws when nothing matches. To check something is gone, use
queryByRole, which returns null.
Show one solution
test("Try again searches again", async () => {
const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime });
render(<TopicSearch />);
await user.type(screen.getByLabelText("Search topics"), "sel!");
await act(() => vi.advanceTimersByTimeAsync(300));
await act(() => vi.advanceTimersByTimeAsync(400));
expect(screen.getByRole("alert").textContent).toContain("The server is having a bad day.");
await user.click(screen.getByRole("button", { name: "Try again" }));
expect(screen.queryByRole("alert")).toBeNull();
expect(screen.getByRole("status").textContent).toBe("Searching…");
await act(() => vi.advanceTimersByTimeAsync(400));
expect(screen.getByRole("alert")).toBeTruthy();
});Add it to TopicSearch.fake.test.jsx.
Completion is saved in this browser only. It does not measure mastery.