Part 14 / Topic 5 of 7
Testing hooks: through a component, and with renderHook
Most of a hook's real coverage should come from testing the component that actually uses it - that is how it is really exercised, clamp-at-the-floor behaviour included:
// examples/05_testing_hooks_via_components_and_renderhook.test.jsx
render(<QuantityStepper />);
await user.click(screen.getByRole("button", { name: "+" }));
expect(screen.getByText("2")).toBeInTheDocument();
renderHook is for exercising a hook's own contract directly, with no UI standing in the way - useful when a hook's internal transitions are worth proving in isolation, or before any real consumer exists yet:
// examples/05_testing_hooks_via_components_and_renderhook.test.jsx
const { result } = renderHook(() => useCartQuantity(3));
act(() => result.current.increment());
expect(result.current.quantity).toBe(4);
Calling a hook's returned function (result.current.increment()) triggers a setState exactly the way a click handler would, so it needs the same act() wrapping. renderHook's rerender is what lets a hook be exercised across a changed argument the way changed props would - and it surfaces a real, worth-seeing gotcha of its own: useCartQuantity's initial argument only feeds useState on the very first render, so rerender({ initial: 5 }) on an already-running hook does not reset anything (examples/05_testing_hooks_via_components_and_renderhook.test.jsx) - the same "initial value vs current value" distinction Part 10 covers for useReducer's lazy init, seen again here from the test side.
Done here? The practice set for Part 14 — including the solutions — is on the part page.