mock with jest code example

Example 1: how to mock a library in jest

import randomColor from "randomcolor";


jest.mock("randomColor", () => {
  return {
    randomColor: () => {
      return mockColor('#123456');
    }
  }
});
let mockColor = jest.fn();

Example 2: 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 3: 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 4: jest mock mockname

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

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