Sub topic 13
Testing hooks with renderHook
This chapter shows how to test a custom hook in isolation. It assumes you can write function components, know useState and useEffect, and have used a test runner such as Jest or Vitest. It also assumes you have seen the useToggle hook from earlier chapters.
Why hooks need a special test setup
A hook can only run inside a component's render. If you call useToggle() directly in a test, React throws an "Invalid hook call" error, because no component is rendering.
You have two options:
- Write a small throwaway component that calls the hook and renders its results. Then test that component.
- Use
renderHookfrom@testing-library/react. It builds that throwaway component for you.
The second option is shorter and keeps the test focused on the hook's contract instead of on markup.
The shape of a basic test
This test is the example from the plan. It renders useToggle, reads the first value, calls the toggle function, and reads the value again.
import { renderHook, act } from '@testing-library/react';
import { useToggle } from './useToggle';
test('useToggle flips its value', () => {
const { result } = renderHook(() => useToggle());
expect(result.current[0]).toBe(false);
act(() => {
result.current[1]();
});
expect(result.current[0]).toBe(true);
});Three parts matter here.
renderHook(callback)calls your callback during the render of a hidden test component. Whatever the callback returns becomes the hook's result.result.currentholds the value from the latest render. It is a getter on a ref-like object, so reading it after an update gives the new value.act(() => { ... })wraps any code that causes a state update. It makes React finish the update and flush effects before the next line runs.
Why you read result.current each time
A common mistake is to destructure the result once and reuse it:
import { renderHook, act } from '@testing-library/react';
import { useToggle } from './useToggle';
test('stale destructuring does not see updates', () => {
const { result } = renderHook(() => useToggle());
const [on, toggle] = result.current;
act(() => {
toggle();
});
// `on` is still the value from the first render.
expect(on).toBe(false);
expect(result.current[0]).toBe(true);
});The variable on is a plain boolean captured from the first render. It never changes. Only result.current is updated. In tests, always read from result.current after each action.
The toggle function is safe to keep, because useToggle returns a stable function through useCallback. For hooks that do not return stable functions, call result.current.someFunction() each time.
Passing props and rerendering
Hooks often take arguments. renderHook accepts an initialProps option, and the callback receives those props. The returned rerender function renders again with new props.
Here is a test for useDebouncedValue. It uses Jest fake timers so the test does not wait in real time.
import { renderHook, act } from '@testing-library/react';
import { useDebouncedValue } from './useDebouncedValue';
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
test('useDebouncedValue waits for the delay', () => {
const { result, rerender } = renderHook(
({ value, delay }) => useDebouncedValue(value, delay),
{ initialProps: { value: 'a', delay: 300 } }
);
expect(result.current).toBe('a');
rerender({ value: 'ab', delay: 300 });
expect(result.current).toBe('a');
act(() => {
jest.advanceTimersByTime(299);
});
expect(result.current).toBe('a');
act(() => {
jest.advanceTimersByTime(1);
});
expect(result.current).toBe('ab');
});The test checks the boundary: at 299 ms the old value remains, and at 300 ms the new value appears. Checking both sides of the boundary catches off-by-one mistakes in the delay.
If you use Vitest, replace jest with vi. The calls vi.useFakeTimers() and vi.advanceTimersByTime() work the same way.
Testing cleanup and unmount
Effects with cleanup are a common source of bugs, so test the cleanup. renderHook returns an unmount function that unmounts the hidden component and runs all cleanup functions.
This test checks that useEventListener removes its listener when the component unmounts. It spies on the target's addEventListener and removeEventListener.
import { renderHook } from '@testing-library/react';
import { useEventListener } from './useEventListener';
test('useEventListener removes its listener on unmount', () => {
const target = new EventTarget();
const addSpy = jest.spyOn(target, 'addEventListener');
const removeSpy = jest.spyOn(target, 'removeEventListener');
const handler = jest.fn();
const { unmount } = renderHook(() =>
useEventListener('ping', handler, target)
);
expect(addSpy).toHaveBeenCalledTimes(1);
target.dispatchEvent(new Event('ping'));
expect(handler).toHaveBeenCalledTimes(1);
unmount();
expect(removeSpy).toHaveBeenCalledTimes(1);
target.dispatchEvent(new Event('ping'));
expect(handler).toHaveBeenCalledTimes(1);
});Using a fresh EventTarget instead of window keeps the test isolated. Nothing leaks between tests, and the spies only see calls from this hook.
The last two lines prove the behavior, not just the call count. After unmount, dispatching the event no longer reaches the handler.
Testing async hooks
Hooks like useFetchJson update state after a promise settles. The state update happens outside your test code, so you cannot wrap it in act yourself. Use waitFor, which polls until a condition holds and wraps the polling in act for you.
import { renderHook, waitFor } from '@testing-library/react';
import { useFetchJson } from './useFetchJson';
afterEach(() => {
jest.restoreAllMocks();
});
test('useFetchJson loads data', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
json: async () => ({ name: 'Ada' }),
});
const { result } = renderHook(() => useFetchJson('/api/user'));
expect(result.current.status).toBe('loading');
await waitFor(() => expect(result.current.status).toBe('success'));
expect(result.current.data).toEqual({ name: 'Ada' });
});
test('useFetchJson reports HTTP errors', async () => {
jest.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: false,
status: 500,
json: async () => ({}),
});
const { result } = renderHook(() => useFetchJson('/api/user'));
await waitFor(() => expect(result.current.status).toBe('error'));
expect(result.current.error.message).toBe('HTTP 500');
});The mock replaces the network. Both tests are deterministic and need no server.
Testing the race condition
The point of useFetchJson is that it ignores outdated responses. A test should prove this. You can make the first request resolve after the second one.
import { renderHook, waitFor } from '@testing-library/react';
import { useFetchJson } from './useFetchJson';
afterEach(() => {
jest.restoreAllMocks();
});
test('useFetchJson ignores a slow, outdated response', async () => {
let resolveFirst;
const first = new Promise((resolve) => {
resolveFirst = resolve;
});
jest
.spyOn(globalThis, 'fetch')
.mockImplementationOnce(() => first)
.mockImplementationOnce(() =>
Promise.resolve({ ok: true, json: async () => ({ id: 2 }) })
);
const { result, rerender } = renderHook(({ url }) => useFetchJson(url), {
initialProps: { url: '/api/1' },
});
rerender({ url: '/api/2' });
await waitFor(() => expect(result.current.status).toBe('success'));
expect(result.current.data).toEqual({ id: 2 });
resolveFirst({ ok: true, json: async () => ({ id: 1 }) });
await Promise.resolve();
expect(result.current.data).toEqual({ id: 2 });
});The first request stays pending until the test releases it. The test then switches the URL, lets the second request finish, and finally resolves the first one. If the hook lacked its ignore flag, the late response would overwrite the data with { id: 1 }.
Testing hooks that need context
Some hooks read from a context provider. renderHook takes a wrapper option for this. The wrapper is a component that receives children and renders them inside the providers you need.
import { createContext, useContext } from 'react';
import { renderHook } from '@testing-library/react';
const ThemeContext = createContext('light');
function useTheme() {
return useContext(ThemeContext);
}
test('useTheme reads the provided theme', () => {
const wrapper = ({ children }) => (
<ThemeContext.Provider value="dark">{children}</ThemeContext.Provider>
);
const { result } = renderHook(() => useTheme(), { wrapper });
expect(result.current).toBe('dark');
});Without the wrapper, the hook would return the default value 'light'. Testing both cases, with and without the wrapper, covers the default and the provided path.
Testing external store hooks
useOnlineStatus reads navigator.onLine and re-renders on online and offline events. In a test, you control both. The act wrapper is needed because the event triggers a state update in React.
import { renderHook, act } from '@testing-library/react';
import { useOnlineStatus } from './useOnlineStatus';
test('useOnlineStatus follows browser events', () => {
const onLine = jest.spyOn(window.navigator, 'onLine', 'get');
onLine.mockReturnValue(true);
const { result } = renderHook(() => useOnlineStatus());
expect(result.current).toBe(true);
act(() => {
onLine.mockReturnValue(false);
window.dispatchEvent(new Event('offline'));
});
expect(result.current).toBe(false);
onLine.mockRestore();
});The test changes the mocked value first, then fires the event. React then calls the snapshot function again and sees the new value.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Calling the hook directly in the test | "Invalid hook call" error | Use `renderHook` |
| Destructuring `result.current` once | Values never change | Read `result.current` after each action |
| Changing state outside `act` | Warning: "not wrapped in act(...)" | Wrap the change in `act`, or use `waitFor` for async changes |
| Using real timers for debounce | Slow, flaky tests | Use fake timers and advance them |
| Not restoring mocks | One test changes another | Restore mocks in `afterEach` |
| Testing internal state | Tests break on refactor | Assert on the returned values and side effects |
When to test through a component instead
A hook that is used by only one component, and only makes sense with that component's markup, is often better tested through the component. Use renderHook when the hook is reusable, has a clear input and output contract, or has tricky logic such as timers, races, or subscriptions.
Exercises
Exercise
A test destructures const [on] = result.current; once, calls the toggle function inside act, and then asserts expect(on).toBe(true). The assertion fails even though the hook works. Why, and how do you fix the test?
Show answer
The variable on is a boolean copied from the first render, so it never changes. Only result.current is replaced on each render. Fix the test by reading result.current[0] after the act call.
Exercise
You are testing a hook that calls fetch and then sets state when the promise resolves. Should you wrap the wait in act or use waitFor, and why?
Show answer
Use waitFor. The state update happens when the promise settles, which your test code does not control. waitFor polls until the assertion passes and handles act for you. Wrapping a fixed delay in act would be slower and could still miss the update.
Exercise
A hook reads a value from UserContext. How do you render it in a test with a user of { name: 'Ada' }?
Show answer
Pass a wrapper option to renderHook. The wrapper is a component that renders children inside <UserContext.Provider value={{ name: 'Ada' }}>. The hook then reads the provided value.