jest reset instance mocks code example

Example 1: jest mock reset

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

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

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

  mockFn.mockReset();
  MockClass.mockReset();

  new MockClass();
  expect(mockFn()).toBeUndefined();

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

Example 2: 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;
});