【问题标题】:Sinon function stubbing: How to call "own" function inside moduleSinon 函数存根:如何在模块内调用“自己的”函数
【发布时间】:2016-05-11 19:12:49
【问题描述】:

我正在为 node.js 代码编写一些单元测试,并使用 Sinon 来存根函数调用

var myFunction = sinon.stub(nodeModule, 'myFunction');
myFunction.returns('mock answer');

nodeModule 看起来像这样

module.exports = {
  myFunction: myFunction,
  anotherF: anotherF
}

function myFunction() {

}

function anotherF() {
  myFunction();
}

Mocking 显然适用于 nodeModule.myFunction() 之类的用例,但我想知道在使用 nodeModule.anotherF() 调用时如何在 anotherF() 中模拟 myFunction() 调用?

【问题讨论】:

    标签: node.js unit-testing sinon


    【解决方案1】:

    你可以稍微重构你的模块。像这样。

    var service = {
       myFunction: myFunction,
       anotherFunction: anotherFunction
    }
    
    module.expors = service;
    
    function myFunction(){};
    
    function anotherFunction() {
       service.myFunction(); //calls whatever there is right now
    }
    

    【讨论】:

    • 很公平 :) 谢谢!
    • 非常感谢!是出于良好实践的原因,还是 Sinon 不提供没有对象引用的存根?
    • @lukas_o 不确定我是否正确理解了您的问题。您可以像 const myStub = sinon.stub() 这样创建一个存根,问题是告诉您的其余代码使用您的存根而不是原始函数。
    • @YuryTarabanko 谢谢,有时您的函数无法注入引用,因此您必须包装 myFunction,就像您在服务中所做的那样。我错过了 var myFunction = sinon.stub('myFunction'); 之类的东西而没有传递对象。
    • @lukas_o 但问题是myFunction 是你的局部变量引用了一个存根,而另一个模块中的myFuncton 引用了完全不同的函数。即使您可以访问它,您也无法更改引用(因为引用是按值传递的)。为此,您需要以某种方式“检测”您加载的模块。像上面的代码一样手动或者说使用rewire 模块。
    猜你喜欢
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2016-05-28
    • 2016-07-11
    • 1970-01-01
    相关资源
    最近更新 更多