Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

358
Views
How to mock parent class manually in Jest?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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") }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!