mock es6 module jest code example

Example 1: jest manual mock node module

// lodash.js
const _ = require('lodash')
module.exports = () => _.repeat('abc', 3)

// lodash.test.js
jest.mock('lodash')
const lodashMock = require('lodash')
const { repeat } = jest.requireActual('lodash')
const lodashRepeat = require('../lodash')

describe('manual mock module', () => {

  beforeEach(() => {
    // setup mock
    lodashMock.repeat.mockReturnValue(repeat('xxx', 3))
  })

  it('lodash repeat value', () => {

    // expect lodashMock
    expect(jest.isMockFunction(lodashMock)).toBeTruthy()

    // expect lodash.js
    expect(lodashRepeat()).toBeDefined()
    expect(lodashRepeat()).toBe("xxxxxxxxx")
    expect(lodashRepeat().length).toBe(9)
  })
})

Example 2: jest mock class

test("es6 class", () => {
    const SomeClass = jest.fn();
    const mMock = jest.fn();

    SomeClass.mockImplementation(() => {
      return {
        m: mMock
      };
    });

    const some = new SomeClass();
    some.m("a", "b");
    expect(mMock.mock.calls).toEqual([["a", "b"]]);
  });

Example 3: jest mock instance

test("mock.instances", () => {
  const mockFn = jest.fn();

  const a = new mockFn();
  const b = new mockFn();

  mockFn.mock.instances[0] === a;
  mockFn.mock.instances[1] === b;
});