Sub topic 13
Testing custom hooks with renderHook
This chapter assumes you can write custom hooks, know how render and screen work, and have Jest or Vitest configured with jsdom. Hooks cannot be called outside a React component, so testing one directly fails. renderHook solves this by running your hook inside a small test component and giving you access to its return value.
When to test a hook on its own
Most hooks are best tested through the components that use them. That approach checks the behavior a user sees. Test a hook directly when it is shared by many components, has logic that is awkward to reach through the UI, or is published as a library.
How renderHook works
renderHook is exported from @testing-library/react (version 13.1 and later). It renders a hidden component that calls your hook. The return value is an object with these properties:
result.currentholds the latest value returned by the hook. It is replaced on every render, so read it again after each change.rerender(newProps)renders the same hook again, optionally with new props.unmount()unmounts the test component, which runs effect cleanups.
A first test
This hook keeps a boolean and returns a function that flips it.
// useToggle.js
import { useCallback, useState } from 'react';
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle];
}
// useToggle.test.js
import { renderHook, act } from '@testing-library/react';
import { useToggle } from './useToggle';
test('toggles the value', () => {
const { result } = renderHook(() => useToggle());
expect(result.current[0]).toBe(false);
act(() => {
result.current[1]();
});
expect(result.current[0]).toBe(true);
});The test reads the initial state from result.current[0]. It then calls toggle inside act. A state update made outside a user event needs act so React applies the update and re-renders before the next line runs. Without it, you get a warning and a stale value.
Passing props and rerendering
Use the initialProps option when the hook takes arguments, and pass new values to rerender.
import { renderHook } from '@testing-library/react';
import { useToggle } from './useToggle';
test('uses the initial value only on the first render', () => {
const { result, rerender } = renderHook(
({ initial }) => useToggle(initial),
{ initialProps: { initial: true } }
);
expect(result.current[0]).toBe(true);
rerender({ initial: false });
expect(result.current[0]).toBe(true);
});The second assertion passes because useState ignores its initial value after the first render. This kind of check is a good use of rerender.
Hooks that need a provider
If the hook calls useContext, pass a wrapper. This is the same option used by the custom render helper in the previous chapter.
import { renderHook } from '@testing-library/react';
import { ThemeProvider } from './ThemeProvider';
import { useTheme } from './useTheme';
test('reads the theme from context', () => {
const { result } = renderHook(() => useTheme(), { wrapper: ThemeProvider });
expect(result.current).toBeDefined();
});Common errors
- Destructuring
result.currentearly. Writingconst [on] = result.currentonce gives you a snapshot that never updates. Readresult.currentafter each action. - Forgetting
act. Calling a state setter returned by the hook withoutactproduces a warning, and the next assertion may see old state. - Importing from the wrong package. Older tutorials use
@testing-library/react-hooks. That package is deprecated and does not support React 18 and later. Import from@testing-library/reactinstead. - Testing implementation details. Assert on what the hook returns, not on how many times it rendered.
Exercise
A test destructures const [count, increment] = result.current right after renderHook, calls act(() => increment()), then asserts expect(count).toBe(1). The assertion fails even though the hook works. Why, and how do you fix it?
Show answer
count is a copy of the value from the first render, so it never changes. After the act call, read result.current[0] again, for example expect(result.current[0]).toBe(1).
Exercise
What does the wrapper option of renderHook do, and when do you need it?
Show answer
It renders the hook's test component inside a given component, usually a context provider. You need it when the hook reads from context, such as a theme or a store, that must be supplied by a provider.