Home > other >  How to mock instance methods of a class mocked with jest.mock?
How to mock instance methods of a class mocked with jest.mock?

Time:05-18

How can the instance methods be mocked for a class that is being mocked with jest.mock?

For example, a class Logger is mocked:

import Person from "./Person";
import Logger from "./Logger";

jest.mock("./Logger");

describe("Person", () => {
  it("calls Logger.method1() on instantiation", () => {
    Logger.method1.mockImplementation(() => {}) // This fails as `method1` is an instance method but how can the instance method be mocked here?
    new Person();
    
    expect(Logger.method1).toHaveBeenCalled();
  });
});

CodePudding user response:

While mocking the Logger class you can provide a module factory as the second argument to jest.mock. You can refer the docs for more information.

import Person from "./Person";

const mockConstructor = jest.fn();
const mockMethod1 = jest.fn();

jest.mock("./Logger.js", () => ({
  default: class mockLogger {
    constructor() {
      mockConstructor();
    }
    method1() {
      mockMethod1();
    }
  },
  __esModule: true
}));

it("works", () => {
  const p = new Person();
  expect(mockConstructor).toHaveBeenCalled();
  p.method1();
  expect(mockMethod1).toHaveBeenCalled();
});
  • Related