Jest mock default and named export


We know that Jest can easily mock a CommonJS module:

jest.mock('./path/to/commonjs', mockedValue);

But what about an ES module?

// esModule.js
export default 'defaultExport';
export const namedExport = () => {};

For Jest to mock the exports, the property __esModule must be enabled in the return value:

// esModule.test.js
jest.mock('./esModule', () => ({
  __esModule: true, // this property makes it work
  default: 'mockedDefaultExport',
  namedExport: jest.fn(),
}));

import defaultExport, { namedExport } from './esModule';
defaultExport; // 'mockedDefaultExport'
namedExport; // mock function