How to Mock useMemo Hook in React
Testing React components sometimes requires mocking built-in hooks to
isolate component behavior, bypass expensive computational overhead, or
assert that a hook is called with correct dependencies. This article
provides a clear, step-by-step guide on how to mock React’s
useMemo hook using Jest, covering both global mocking and
test-specific spying.
Method 1: Mocking useMemo with jest.spyOn
The most flexible way to mock useMemo is by using
jest.spyOn. This approach allows you to mock the hook for
individual tests and easily restore its original implementation
afterward so it does not interfere with other tests.
To mock useMemo to simply return the result of its
callback function immediately, use the following code:
import React from 'react';
import { render } from '@testing-library/react';
import MyComponent from './MyComponent';
describe('MyComponent', () => {
let useMemoSpy;
beforeEach(() => {
// Spy on React.useMemo and force it to execute and return the callback's result
useMemoSpy = jest.spyOn(React, 'useMemo').mockImplementation((callback) => callback());
});
afterEach(() => {
// Restore the original useMemo implementation
useMemoSpy.mockRestore();
});
it('should render with mocked useMemo', () => {
render(<MyComponent />);
expect(useMemoSpy).toHaveBeenCalled();
});
});By passing (callback) => callback() to
mockImplementation, you bypass React’s internal caching
mechanism and immediately execute the factory function passed to
useMemo.
Method 2: Mocking useMemo Globally via jest.mock
If you want to mock useMemo globally for an entire test
file, you can mock the react module. Because you still need
the rest of React’s features (like useState or
useEffect) to work normally, you must use
jest.requireActual to preserve them.
Place this mock at the top of your test file:
import React from 'react';
jest.mock('react', () => ({
...jest.requireActual('react'),
useMemo: jest.fn((callback) => callback()),
}));With this mock in place, every component rendered within this test file will bypass the traditional memoization logic and simply run the computed function on every render.
Mocking Specific Return Values
If your goal is to force useMemo to return a specific
mock value regardless of the inputs, you can override the implementation
to return a static value:
const mockData = { id: 1, name: 'Mocked Data' };
jest.spyOn(React, 'useMemo').mockReturnValue(mockData);This is highly useful when testing UI states that depend on complex
data structures generated inside the useMemo block.