jest mock new instance jest.mock code example

Example 1: 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 2: jest mockclear

test("mockFn.mockClear", () => {
  const mockFn = jest.fn().mockImplementation(() => 42);
  const MockClass = jest.fn();

  new MockClass();
  expect(mockFn()).toBe(42);

  expect(mockFn.mock.calls).toHaveLength(1);
  expect(MockClass.mock.instances).toHaveLength(1);

  new MockClass();
  expect(mockFn()).toBe(42);

  expect(mockFn.mock.calls).toHaveLength(2);
  expect(MockClass.mock.instances).toHaveLength(2);

  mockFn.mockClear();
  MockClass.mockClear();

   new MockClass();
  expect(mockFn()).toBe(42);

  expect(mockFn.mock.calls).toHaveLength(1);
  expect(MockClass.mock.instances).toHaveLength(1);
  
});