0

Let's imagine to functions, a and b.

function a() {
    return 5;
}

function b() {
    return a() + 5;
}

module.exports = { a, b };

To properly test b, I want to mock a. To do this, I try jest.mock:

const { a, b } = require("./myFunctions");

jest.mock("./myFunctions", () => ({
  ...jest.requireActual("./myFunctions"),
  a: jest.fn(() => 10),
}));

describe("myFunctions", () => {
  it("mocks a", () => {
    expect(a()).toEqual(10);
  });

  it("mock affects b", () => {
    expect(b()).toEqual(15);
  });
});

The first test succeeds: a returns 10 instead of 5 as expected. However, the latter test fails because when b calls a, it still returns 5.

How do I mock a so that it's effective in b calls?

MikkoP
  • 4,864
  • 16
  • 58
  • 106

0 Answers0