Mocking Modules in Jest

·

1 min read

Example 1

CommonJS system is used.

|index.js|

module.exports.increment = function (num) {
  return num + 1;
};

|index.test.js|

const { expect, test } = require('@jest/globals');
const m = require('./index');

jest.mock('./index', () => {
  // (1)
  // const originalModule = jest.requireActual('./index');

  return {
    // (1)
    // ...originalModule,
    // (2)
    // __esModule: false,
    increment: (num) => num + 2,
  };
});

test('mock increment', () => {
  expect(m.increment(1)).toBe(3);
});

Commented parts can be uncommented.