A hook can only run inside a component. In Intermediate you wrote a tiny
component to call one. renderHook does that for you: it renders a hidden
component that calls your hook, and gives you what it returned.
The first test
Create src/useDebouncedValue.test.js:
import { act, renderHook } from "@testing-library/react";
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { useDebouncedValue } from "./useDebouncedValue.js";
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
test("starts with the first value", () => {
const { result } = renderHook(() => useDebouncedValue("a", 300));
expect(result.current).toBe("a");
});
test("changes only after the value has been still for the delay", () => {
const { result, rerender } = renderHook(({ value }) => useDebouncedValue(value, 300), {
initialProps: { value: "a" },
});
rerender({ value: "ab" });
act(() => vi.advanceTimersByTime(299));
expect(result.current).toBe("a");
act(() => vi.advanceTimersByTime(1));
expect(result.current).toBe("ab");
});
test("each change restarts the wait", () => {
const { result, rerender } = renderHook(({ value }) => useDebouncedValue(value, 300), {
initialProps: { value: "a" },
});
rerender({ value: "ab" });
act(() => vi.advanceTimersByTime(200));
rerender({ value: "abc" });
act(() => vi.advanceTimersByTime(200));
expect(result.current).toBe("a");
act(() => vi.advanceTimersByTime(100));
expect(result.current).toBe("abc");
});Run npm test. All three pass.
How it works
renderHook(callback, { initialProps })callscallbackinside a component.result.currentis the hook's latest return value. Read it after each step, never save it in a variable early: it's replaced on every render.rerender(props)renders again with new props, as a parent would when its state changes. The callback gets them as its argument.vi.useFakeTimers()replacessetTimeoutand friends with a clock the test controls. Nothing waits for real:vi.advanceTimersByTime(299)jumps the clock forward and runs every timer due by then.act(...)wraps anything that makes React update outside a render or an event, such as a timer firing. React applies the updates beforeactreturns, soresult.currentis up to date on the next line.afterEachputs real timers back, so one test's fake clock can't leak into the next.
Prove the test can fail
A test that has never failed might not be testing anything. In
useDebouncedValue.js, delete the cleanup line,
return () => clearTimeout(id);, and save:
export function useDebouncedValue(value, delay) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(id);
}, [value, delay]);
return debounced;
}What happens
each change restarts the wait fails: without the cleanup, the timer from ab still fires 300 ms after it started, so the value changes to ab while you're still typing. The other two tests still pass, which is why each behaviour gets its own test. Put the line back.
A new delay
Write a test that changing the delay prop is respected: start with
{ value: "a", delay: 300 }, rerender with { value: "ab", delay: 1000 },
and check the value changes at 1000 ms, not before.
Hint 1: the idea
Make the delay an input the test can change. Check the boundary just before and just after the new wait expires.
Hint 2: a first step
Put both value and delay in initialProps, and pass both to the hook:
({ value, delay }) => useDebouncedValue(value, delay).
Show one solution
test("a new delay is used for the next change", () => {
const { result, rerender } = renderHook(({ value, delay }) => useDebouncedValue(value, delay), {
initialProps: { value: "a", delay: 300 },
});
rerender({ value: "ab", delay: 1000 });
act(() => vi.advanceTimersByTime(999));
expect(result.current).toBe("a");
act(() => vi.advanceTimersByTime(1));
expect(result.current).toBe("ab");
});Completion is saved in this browser only. It does not measure mastery.