To mock React custom hook returned value with Jest, we can call jest.mock
.
For instance, we write:
jest.mock('module_name', () => ({
useRect: () => [300, 200, jest.fn()]
}));
to call jest.mock
with the module name and the function to mock the useRect
hook with a function that returns the mocked values of the hook.
If we want to mock the hook once for a test, then use jest.spyOn
with
import * as hooks from 'module_name';
it('a test', () => {
jest.spyOn(hooks, 'useRect').mockImplementation(() => ([100, 200, jest.fn()]));
// ...
});
to mock the useRect
hook and return the mocked return values with mockImplementation
.
We can just mock the return values since hooks are pure functions so they don’t commit side effects.