乐闻世界logo
搜索文章和话题

How to test React Hooks in Jest? How to use renderHook and act?

2月21日 15:57

Jest provides multiple methods for testing React Hooks, primarily using @testing-library/react-hooks:

1. Testing useState:

javascript
import { 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:

javascript
test('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:

javascript
test('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:

javascript
function 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:

javascript
test('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:

javascript
test('hook error handling', async () => { const { result, waitForNextUpdate } = renderHook(() => useFetch('/invalid')); await waitForNextUpdate(); expect(result.current.error).toBeInstanceOf(Error); });

Best Practices:

  • Use renderHook to test hooks
  • Use act to wrap state updates
  • Test initial state and updated state of hooks
  • Use waitFor or waitForNextUpdate for async hooks
  • Test error boundary cases
  • Keep tests simple, focus on hook behavior
标签:JestReact Hook