How to Perform Hooks Testing in React

Pascual Vila
Frontend Instructor.
Hooks testing in React is essential to ensure that the reusable logic encapsulated in your custom hooks functions as expected, regardless of the components that use them. Since hooks are JavaScript functions, they can be tested in isolation, but often require a React environment to simulate their lifecycle.
Tools for testing Hooks:
- @testing-library/react-hooks (deprecated, now part of @testing-library/react): This library is the recommended way to test custom hooks. It allows you to render hooks in an isolated test component and access their values and method calls.
- Jest: Used as the main test runner in conjunction with testing libraries.
Example of testing a custom hook with React Testing Library:
{`// useCounter.js
import { useState, useCallback } from 'react';
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = useCallback(() => {
setCount(prevCount => prevCount + 1);
}, []);
const decrement = useCallback(() => {
setCount(prevCount => prevCount - 1);
}, []);
return { count, increment, decrement };
}
export default useCounter;
// useCounter.test.js
import { renderHook, act } from '@testing-library/react';
import useCounter from './useCounter';
describe('useCounter', () => {
it('should increment the counter', () => {
const { result } = renderHook(() => useCounter());
act(() => {
result.current.increment();
});
expect(result.current.count).toBe(1);
});
it('should decrement the counter', () => {
const { result } = renderHook(() => useCounter(5));
act(() => {
result.current.decrement();
});
expect(result.current.count).toBe(4);
});
it('should set initial value', () => {
const { result } = renderHook(() => useCounter(10));
expect(result.current.count).toBe(10);
});
});`}
The renderHook function from @testing-library/react (or @testing-library/react-hooks) creates a simple functional component to render the hook, allowing you to simulate its lifecycle. The act function ensures that all state updates related to the test are processed before making assertions.