12. Testing React Hooks and Custom Hooks
React hooks have changed how we write React components. Testing hooks requires different techniques than testing components. This module covers testing built-in hooks and custom hooks with React Testing Library and @testing-library/react.
The key insight is that hooks are tested by rendering a component that uses them. React Testing Library provides the renderHook function for testing hooks in isolation. Understanding how to test hooks is essential for modern React development.
This module covers testing useState, useEffect, useContext, useReducer, and custom hooks.
Testing Built-in Hooks
Testing hooks involves rendering a component that uses the hook and verifying the behavior. For useState, you verify state updates. For useEffect, you verify side effects. For useContext, you verify context values. For useReducer, you verify state updates and dispatches.
The key is to test the behavior, not the hook itself. Test what the hook does, not how it does it. This makes your tests more resilient to implementation changes.
Testing Custom Hooks with renderHook
renderHook is a function from @testing-library/react that renders a hook in a test component. It returns the hook's result and utilities like rerender and unmount. This makes it easy to test custom hooks in isolation.
Custom hooks are tested by calling renderHook, interacting with the hook's API, and verifying the behavior. This is the most reliable way to test custom hooks.
// Custom hook: useCounter import { useState } from 'react'; export function useCounter(initialCount = 0) { const [count, setCount] = useState(initialCount); const increment = () => setCount(count + 1); const decrement = () => setCount(count - 1); const reset = () => setCount(initialCount); return { count, increment, decrement, reset }; } // Custom hook: useLocalStorage import { useState, useEffect } from 'react'; export function useLocalStorage(key, initialValue) { const [storedValue, setStoredValue] = useState(() => { try { const item = localStorage.getItem(key); return item ? JSON.parse(item) : initialValue; } catch (error) { return initialValue; } }); useEffect(() => { localStorage.setItem(key, JSON.stringify(storedValue)); }, [key, storedValue]); return [storedValue, setStoredValue]; } // Testing custom hooks import { renderHook, act } from '@testing-library/react'; import { useCounter, useLocalStorage } from './hooks'; describe('useCounter', () => { test('initializes with default value', () => { const { result } = renderHook(() => useCounter()); expect(result.current.count).toBe(0); }); test('initializes with provided value', () => { const { result } = renderHook(() => useCounter(10)); expect(result.current.count).toBe(10); }); test('increments count', () => { const { result } = renderHook(() => useCounter(0)); act(() => result.current.increment()); expect(result.current.count).toBe(1); act(() => result.current.increment()); expect(result.current.count).toBe(2); }); test('decrements count', () => { const { result } = renderHook(() => useCounter(5)); act(() => result.current.decrement()); expect(result.current.count).toBe(4); }); test('resets count', () => { const { result } = renderHook(() => useCounter(5)); act(() => result.current.increment()); expect(result.current.count).toBe(6); act(() => result.current.reset()); expect(result.current.count).toBe(5); }); }); describe('useLocalStorage', () => { beforeEach(() => { localStorage.clear(); }); test('reads initial value from localStorage', () => { localStorage.setItem('test', JSON.stringify('saved')); const { result } = renderHook(() => useLocalStorage('test', 'default')); expect(result.current[0]).toBe('saved'); }); test('uses default value when localStorage is empty', () => { const { result } = renderHook(() => useLocalStorage('test', 'default')); expect(result.current[0]).toBe('default'); }); test('saves value to localStorage', () => { const { result } = renderHook(() => useLocalStorage('test', 'default')); act(() => result.current[1]('updated')); expect(result.current[0]).toBe('updated'); expect(localStorage.getItem('test')).toBe(JSON.stringify('updated')); }); });
Try It Yourself: Testing Custom Hooks
Follow these steps to practice testing custom hooks.
Step 1: Create a custom hook// useFetch.js<br>import { useState, useEffect } from <strong><code>react;
export function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch(url)
.then(res => res.json())
.then(data => {
setData(data);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, [url]);
return { data, loading, error };
}
Step 2: Write tests for the hook// useFetch.test.js<br>import { renderHook } from <strong><code>@testing-library/react;
import { useFetch } from ./useFetch;
describe(useFetch, () => {
test(fetches data successfully, async () => {
const mockData = { id: 1, name: Test };
global.fetch = jest.fn().mockResolvedValue({
json: jest.fn().mockResolvedValue(mockData)
});
const { result, waitForNextUpdate } = renderHook(() =>
useFetch(https://api.example.com/data)
);
expect(result.current.loading).toBe(true);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toEqual(mockData);
expect(result.current.error).toBe(null);
});
test(handles error, async () => {
global.fetch = jest.fn().mockRejectedValue(new Error(Network error));
const { result, waitForNextUpdate } = renderHook(() =>
useFetch(https://api.example.com/data)
);
await waitForNextUpdate();
expect(result.current.loading).toBe(false);
expect(result.current.data).toBe(null);
expect(result.current.error).toBe(Network error);
});
});
Try It Yourself: Create a custom hook for form handling. Write tests for the hook.
Knowledge Check
Ready to test your understanding of 12. Testing React Hooks and Custom Hooks?