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
?