mock jest.fn code example

Example 1: jest mock implementation

describe("mockImplementation", () => {
  test("function", () => {
    const mockFn1 = jest.fn().mockImplementation(() => 42);
    const mockFn2 = jest.fn(() => 42);

    expect(mockFn1()).toBe(42);
    expect(mockFn2()).toBe(42);
  });

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