1

I thought I'd be able to spyOn a function in my module but it doesn't register as being called even though it obviously was. Here's a boiled down sample.js:

const func1 = () => {
  return func2();
};

const func2 = () => {
  return "func2 called";
};

module.exports = { func1, func2 };

and here is its jest test in ./__tests__/sample.test.js:

const sample = require("../sample");

describe("sample", () => {
  it("should spy on func2", () => {
    jest.spyOn(sample,"func2");
    const f = sample.func1();
    console.log(f);                          // outputs "func2 called" correctly
    expect(sample.func2).toHaveBeenCalled(); // fails
  });
});

The test fails with:

Expected mock function to have been called, but it was not called.

It works correctly if I spy on func1 instead but why not with the function called by func1?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Always Learning
  • 5,510
  • 2
  • 17
  • 34
  • Also answered here for the more general case of mocking the function: [Jest mock inner function](https://stackoverflow.com/questions/51269431/jest-mock-inner-function) – Brian Adams Sep 21 '19 at 16:13

1 Answers1

0

I think maybe you need to do the expect on the return value of jest.spyOn(sample, "func2");

So your test would look something like:

    const spy = jest.spyOn(sample,"func2");
    const f = sample.func1();
    console.log(f);
    expect(spy).toHaveBeenCalled();

From jest's official docs: https://jestjs.io/docs/en/jest-object#jestspyonobject-methodname