jest fn mock 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 spy on class method

//class.js
class MyClass {
  methodOne() {
    return 1;
  }
  methodTwo() {
    return 2;
  }
}
module.exports = MyClass;

// class.test.js
test('spy using class method', () => {
  const result = new MyClass()
  const spy = jest.spyOn(result, 'methodOne')
  result.methodOne()

  // check class method is call or not
  expect(spy).toHaveBeenCalled()

  // expect old value
  expect(result.methodOne()).toBe(1)

  // expect new value
  spy.mockReturnValueOnce(12)
  expect(result.methodOne()).toBe(12)
})