Home > database >  How to mock parent class manually in Jest?
How to mock parent class manually in Jest?

Time:06-04

I want to change a base class methods return values. But i couldn't find any content for this. Please help.

I am going to give an example.

A base class:

class ParentClass {
  save() {
    return "saved";
  }
}

A child class:

class ChildClass extends ParentClass {}

And I tried this:

The code below is inside a folder named mocks/parent.js.

const ParentClass = jest.fn().mockReturnValue({
  save: jest.fn().mockReturnValue("mocked"),
});

Finally this is my test file.

child.spec.js

jest.mock("./parent");

it("should be return mocked value", () => {
  const child = new ChildClass();

  expect(child.save()).toBe("mocked");
});

The test code above doesn't work. Because it gives the following error.

enter image description here

How can i solve this? Thanks.

CodePudding user response:

I couldn't mock the Parent class but I found a tricky solution.

jest.spyOn(ParentClass.prototype,"save").mockReturnValue("mocked");

So the test code below works without any problem.

it("should be called", () => {
  

  const child = new ChildClass();

  jest.spyOn(ParentClass.prototype, "save").mockReturnValue("mocked");

  expect(child.save()).toBe("mocked");
});

CodePudding user response:

Jest executes jest.mock first before evaluating any imported modules in your test suite, hence you will need to have the mock defined within your test suite.

This should look as follows:

jest.mock("./parent", () => ({
  ParentClass: jest.fn().mockImplementation(() => ({
    save: jest.fn().mockReturnValue("mocked"),
  }))
}));

Explanation:

  • ./parent need to be a relative path to the parent module that you are looking to mock out.
  • Because ParentClass is a named export, the returned mock object needs to have a key with the same name
  • We need to use jest.fn().mockImplementation to allow a new class instance to be created, which will then return a new object with { save: jest.fn().mockReturnValue("mocked") }
  • Related