Code Reference

Module Mocks

Jest · Reference cheat sheet

Module Mocks

Jest · Reference cheat sheet


📋 Overview

Automock modules with jest.mock, manual __mocks__ folders, and virtual mocks. Control Node built-ins and CSS/assets via mappers.

🔧 Core concepts

TechniqueWhen
jest.mock('./mod')Auto mock or factory
__mocks__/mod.jsShared manual mock
jest.requireActualPartial mock
moduleNameMapperAssets / aliases
jest.unstable_mockModuleESM (experimental)

Factories run in a sandboxed scope; hoist rules apply to jest.mock.

💡 Examples

Manual mock:

src/
  api.js
  __mocks__/
    api.js
// __mocks__/api.js
export const getUser = jest.fn();
jest.mock('./api');
import { getUser } from './api';
getUser.mockResolvedValue({ id: 1 });

Virtual mock:

jest.mock('analytics', () => ({ track: jest.fn() }), { virtual: true });

Asset mapper:

moduleNameMapper: {
  '\\.svg$': '<rootDir>/test/svgrMock.js',
  '\\.(css)$': 'identity-obj-proxy',
},

Unmock / isolate:

jest.unmock('./api');
jest.isolateModules(() => {
  const mod = require('./fresh');
});

⚠️ Pitfalls

  • Factory referencing out-of-scope variables (TDZ / hoist).
  • Manual mocks not picked up because path casing/OS differs.
  • Mocking ESM named exports incorrectly (namespace shape).
  • Leaving automock on globally (automock: true) — surprising.
  • Circular deps with requireActual causing partial undefineds.

On this page