Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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();
  });
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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();
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading