Jest provides multiple methods for testing React Hooks, primarily using @testing-library/react-hooks:
1. Testing useState:
javascriptimport { renderHook, act } from '@testing-library/react-hooks'; test('useState hook', () => { const { result } = renderHook(() => useCounter(0)); expect(result.current.count).toBe(0); act(() => { result.current.increment(); }); expect(result.current.count).toBe(1); });
2. Testing useEffect:
javascripttest('useEffect hook', () => { const { result } = renderHook(() => useFetch('/api/data')); expect(result.current.loading).toBe(true); await act(async () => { await waitFor(() => !result.current.loading); }); expect(result.current.data).toBeDefined(); });
3. Testing useContext:
javascripttest('useContext hook', () => { const wrapper = ({ children }) => ( <ThemeContext.Provider value="dark"> {children} </ThemeContext.Provider> ); const { result } = renderHook(() => useTheme(), { wrapper }); expect(result.current.theme).toBe('dark'); });
4. Testing Custom Hooks:
javascriptfunction useCustomHook(initialValue) { const [value, setValue] = useState(initialValue); const double = useMemo(() => value * 2, [value]); return { value, setValue, double }; } test('custom hook', () => { const { result } = renderHook(() => useCustomHook(5)); expect(result.current.value).toBe(5); expect(result.current.double).toBe(10); act(() => { result.current.setValue(10); }); expect(result.current.double).toBe(20); });
5. Testing Async Hooks:
javascripttest('async hook', async () => { const { result, waitForNextUpdate } = renderHook(() => useAsyncData()); expect(result.current.loading).toBe(true); await waitForNextUpdate(); expect(result.current.loading).toBe(false); expect(result.current.data).toBeDefined(); });
6. Testing Error Handling:
javascripttest('hook error handling', async () => { const { result, waitForNextUpdate } = renderHook(() => useFetch('/invalid')); await waitForNextUpdate(); expect(result.current.error).toBeInstanceOf(Error); });
Best Practices:
- Use
renderHookto test hooks - Use
actto wrap state updates - Test initial state and updated state of hooks
- Use
waitFororwaitForNextUpdatefor async hooks - Test error boundary cases
- Keep tests simple, focus on hook behavior