Jest mock Node module in Create React App


This post goes over how to mock node_modules using Jest in Create React App.

Mock function

A mock function is created directly in the test code.

Use jest.mock to auto-mock a module:

// src/test.js
import lodash from 'lodash';

jest.mock('lodash');

it('mocks lodash', () => {
  expect(jest.isMockFunction(lodash)).toBe(true);
});

To mock a module export, use jest.fn:

// src/test.js
// ...
lodash.get = jest.fn();

it('mocks lodash.get', () => {
  expect(jest.isMockFunction(lodash.get)).toBe(true);
});

Or specify a module factory in jest.mock:

// src/test.js
import lodash from 'lodash';

jest.mock('lodash', () => ({
  get: jest.fn(),
}));

it('mocks lodash.get', () => {
  expect(jest.isMockFunction(lodash.get)).toBe(true);
});

Manual mock

A manual mock is a stub that overrides a module dependency.

From the docs:

If the module you are mocking is a Node module, the mock should be placed in the __mocks__ directory adjacent to node_modules.

However, this doesn’t work for Create React App because roots is configured to point to '<rootDir>/src/'.

As a result, the module must be placed in the __mocks__ directory adjacent to <rootDir>/src/:

.
└── src
    └── __mocks__
        └── lodash.js
// src/__mocks__/lodash.js
export const get = jest.fn();
// src/test.js
import lodash from 'lodash';

it('mocks lodash.get', () => {
  expect(jest.isMockFunction(lodash.get)).toBe(true);
});

See GitHub issue facebook/create-react-app##7539 for more information.



Please support this site and join our Discord!