How to mock React custom hook returned value with Jest?

Sometimes, we want to mock React custom hook returned value with Jest.

In this article, we’ll look at how to mock React custom hook returned value with Jest.

How to mock React custom hook returned value with Jest?

To mock React custom hook returned value with Jest, we can call jest.mock.

For instance, we write:

jest.mock('module_name', () => ({
  useClientRect: () => [300, 200, jest.fn()]
}));

to call jest.mock with the module name and the function to mock the useClientRect 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, 'useClientRect').mockImplementation(() => ([100, 200, jest.fn()]));
  // ...
});

to mock the useClientRect 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.

Conclusion

To mock React custom hook returned value with Jest, we can call jest.mock.