Javascript 呼叫链较深时未呼叫Jest spyOn

Javascript 呼叫链较深时未呼叫Jest spyOn,javascript,jestjs,spyon,Javascript,Jestjs,Spyon,我原以为我可以spyOn在我的模块中调用一个函数,但它没有注册为被调用,即使它显然是被调用的。下面是一个简化的sample.js: const func1 = () => { return func2(); }; const func2 = () => { return "func2 called"; }; module.exports = { func1, func2 }; const sample = require("../sample"); describe(

我原以为我可以
spyOn
在我的模块中调用一个函数,但它没有注册为被调用,即使它显然是被调用的。下面是一个简化的
sample.js

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

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

module.exports = { func1, func2 };
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
  });
});
下面是它在
/\uuuuu tests\uuuu/sample.test.js中的jest测试:

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

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

module.exports = { func1, func2 };
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
  });
});
测试失败,原因是:

预期已调用模拟函数,但未调用该函数


如果我监视
func1
,它可以正常工作,但是为什么不使用
func1
调用的函数呢?

我想您可能需要对
jest.spyOn(示例,“func2”)的返回值执行预期操作

所以你的测试看起来像:

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

来自jest的官方文档:

我确实尝试过,但结果相同。因此,这里回答了模拟函数的更一般情况: