jest spy mock implementation code example

Example 1: jest spyon

// jest.spyOn(object, methodName)
const spy = jest.spyOn(video, 'play');

// jest.spyOn(object, methodName, accessType?)
const spy = jest.spyOn(video, 'play', 'get'); // we pass 'get'

Example 2: jest mock mockname

test("mockName", () => {
  const mockFn = jest.fn().mockName("mockedFunction");
  mockFn(); // comment me
  expect(mockFn).toHaveBeenCalled();
});

Example 3: jest mock restore

// equvalent to mockReset

test("mockFn.mockRestore", () => {
  const StringUtils = {
    toUpperCase(arg) {
      return arg && arg.toUpperCase();
    }
  };

  const spy = jest.spyOn(StringUtils, "toUpperCase").mockImplementation(() => "MOCK");

  expect(StringUtils.toUpperCase("arg")).toBe("MOCK");
  expect(spy).toHaveBeenCalledTimes(1);
  expect(jest.isMockFunction(StringUtils.toUpperCase)).toBeTruthy();

  spy.mockRestore();

  expect(spy("arg")).toBeUndefined();
  expect(jest.isMockFunction(StringUtils.toUpperCase)).not.toBeTruthy();
  expect(StringUtils.toUpperCase("arg")).toBe("ARG");
  expect(spy).toHaveBeenCalledTimes(1);
 
});