繁体   English   中英

Jest spyOn 无法识别 function 调用

[英]Jest spyOn doesn't recognize function call

我有一个具有两个功能的节点模块:

authenticate()signIn()

authenticate调用signIn作为助手 function 都从模块中导出,如下所示:

module.exports = { authenticate, signIn };

我正在遵循针对此处发现的类似问题的建议: 预期 spyOn function to be called Jest

在我的测试结果中注销模块的内容以确认两种方法都存在:

      {
        authenticate: [AsyncFunction: authenticate],
        signIn: [AsyncFunction: signIn]
      }

我在测试authenticationsignIn登录以确保它被调用,并且我知道它被调用是因为来自登录的消息signIn到控制台。 我希望这个测试能够通过,但是它没有说当预期 >=1 时有 0 个调用。

const auth = require("./authenticate");

test("should signIn", async () => {
  console.log(auth);
  const signInSpy = jest.spyOn(auth, "signIn").mockResolvedValue({ access_token: "123" });
  await auth.authenticate();
  expect(signInSpy).toBeCalled();
});

我假设我设置错误,因为调用auth.authenticate()实际上调用了auth模块的signIn ,但我不知道它是什么。

如果您的authenticate.js代码如下所示,其中 authenticate 直接调用signIn ,Jest 不会模拟该值,因为它是对原始 function 的引用,而不是导出的 object 上的属性。

// Doesn't work
const signIn = () => console.log("Signed in");
// `signIn` will never be anything other than the function above
const authenticate = () => signIn();

module.exports = {
  authenticate,
  signIn
};

如果您直接或通过使用module.exports this ,您将能够在测试中从 Jest 访问间谍版本。

// Works
module.exports.signIn = () => console.log("Signed in");
module.exports.authenticate = () => module.exports.signIn();
// Also works
module.exports = {
  authenticate: function () {
    this.signIn();
  },
  signIn: () => console.log("Signed in")
};

如果这些解决方案不适用于您的原始代码,您可能希望部分模拟 authenticate.js 模块,或者将您的函数分离到不同的文件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM