The real api.js always answers in 400 ms and fails only on !. Real
servers are slower, faster, down, or answer out of order. To test the hook's
handling of each, the test must decide what the server does.
vi.mock
Create src/useTopicSearch.test.js:
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { searchTopics } from "./api.js";
import { useTopicSearch } from "./useTopicSearch.js";
vi.mock("./api.js", () => ({ searchTopics: vi.fn() }));
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
vi.resetAllMocks();
});
test("asks the server once typing pauses, and returns its answer", async () => {
searchTopics.mockResolvedValue(["Selectors"]);
const { result, rerender } = renderHook(({ query }) => useTopicSearch(query), {
initialProps: { query: "" },
});
rerender({ query: "sel" });
await act(() => vi.advanceTimersByTimeAsync(299));
expect(result.current.status).toBe("idle");
expect(searchTopics).not.toHaveBeenCalled();
await act(() => vi.advanceTimersByTimeAsync(1));
expect(searchTopics).toHaveBeenCalledTimes(1);
expect(searchTopics).toHaveBeenCalledWith("sel");
expect(result.current).toMatchObject({ status: "done", results: ["Selectors"] });
});
test("a failure becomes the error state, and retry asks again", async () => {
searchTopics.mockRejectedValueOnce(new Error("Offline")).mockResolvedValueOnce(["Selectors"]);
const { result } = renderHook(() => useTopicSearch("sel"));
await act(() => vi.advanceTimersByTimeAsync(300));
expect(result.current.status).toBe("error");
expect(result.current.error.message).toBe("Offline");
await act(async () => result.current.retry());
expect(searchTopics).toHaveBeenCalledTimes(2);
expect(result.current).toMatchObject({ status: "done", results: ["Selectors"] });
});
test("a slow answer to an old search never replaces a newer one", async () => {
let answerFirst;
searchTopics
.mockReturnValueOnce(new Promise((resolve) => { answerFirst = resolve; }))
.mockResolvedValueOnce(["State machines"]);
const { result, rerender } = renderHook(({ query }) => useTopicSearch(query), {
initialProps: { query: "s" },
});
await act(() => vi.advanceTimersByTimeAsync(300));
rerender({ query: "state" });
await act(() => vi.advanceTimersByTimeAsync(300));
expect(result.current.results).toEqual(["State machines"]);
await act(async () => answerFirst(["Selectors", "Suspense"]));
expect(result.current.results).toEqual(["State machines"]);
});vi.mock("./api.js", factory)replaces the module for this test file. Every import of./api.js, including the one insideuseTopicSearch.js, gets the factory's object instead. Vitest movesvi.mockto the top of the file, so it applies before the imports run.vi.fn()is a function that records its calls. Import it as normal, then checktoHaveBeenCalledTimesandtoHaveBeenCalledWith.mockResolvedValue(x)makes it return a promise ofx.mockRejectedValueOnceandmockResolvedValueOnceset one answer each, in order.vi.resetAllMocks()clears the recorded calls and answers after each test.
Starting from empty
The first test renders with "", then changes to sel. If it started with
sel, the hook would search straight away: useDebouncedValue starts with
its first value, so there's nothing to wait for. Starting empty is how a person
uses it.
The race
The third test controls when an answer arrives. The first call returns a
promise the test resolves by hand, after the second search has finished. That's
the case ignore handles: without it, the old answer for s would replace
the newer one for state.
Try it: in useTopicSearch.js, change
if (!ignore) setState({ status: "done", ... to just setState({ status: "done", ....
What happens
a slow answer to an old search never replaces a newer one fails: the
results become Selectors, Suspense. A bug like that is almost impossible to
catch by hand, because it depends on the network's timing. Put if (!ignore)
back.
When to mock
Mock at the edge of your app: the network, the clock, storage. Don't mock
your own components or hooks to test another one; then you're testing that the
mocks agree with each other. The component tests in the last lesson used the
real api.js and checked the whole path, and these hook tests cover the timing
that's hard to produce for real. Together they're a good split.
Clearing the search
Test that clearing the search goes back to idle with no results, and doesn't ask the server again.
Hint 1: the idea
Clearing is a state transition with two observable requirements: empty results and no additional request.
Hint 2: a first step
Search for sel first and wait 300 ms. Then rerender({ query: "" }), wait
again, and check both the result and toHaveBeenCalledTimes(1).
Show one solution
test("clearing the search goes back to idle without asking the server", async () => {
searchTopics.mockResolvedValue(["Selectors"]);
const { result, rerender } = renderHook(({ query }) => useTopicSearch(query), {
initialProps: { query: "sel" },
});
await act(() => vi.advanceTimersByTimeAsync(300));
expect(result.current.status).toBe("done");
rerender({ query: "" });
await act(() => vi.advanceTimersByTimeAsync(300));
expect(result.current).toMatchObject({ status: "idle", results: [] });
expect(searchTopics).toHaveBeenCalledTimes(1);
});Completion is saved in this browser only. It does not measure mastery.