Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js Sinon函数存根:如何调用;“拥有”;模块内部的函数_Node.js_Unit Testing_Sinon - Fatal编程技术网

Node.js Sinon函数存根:如何调用;“拥有”;模块内部的函数

Node.js Sinon函数存根:如何调用;“拥有”;模块内部的函数,node.js,unit-testing,sinon,Node.js,Unit Testing,Sinon,我正在为node.js代码编写一些单元测试,并使用Sinon通过 var myFunction = sinon.stub(nodeModule, 'myFunction'); myFunction.returns('mock answer'); nodeModule如下所示 module.exports = { myFunction: myFunction, anotherF: anotherF } function myFunction() { } function anoth

我正在为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();
}

mock显然适用于像
nodeModule.myFunction()
这样的用例,但我想知道当使用
nodeModule.anotherF()调用时,如何在另一个()中模拟myFunction()调用?

您可以稍微重构一下模块。像这样

var service = {
   myFunction: myFunction,
   anotherFunction: anotherFunction
}

module.expors = service;

function myFunction(){};

function anotherFunction() {
   service.myFunction(); //calls whatever there is right now
}

您可以稍微重构一下您的模块。像这样

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
在另一个模块中引用完全不同的函数。即使您有权访问引用,也不能更改引用(因为引用是按值传递的)。要做到这一点,您需要以某种方式“插入”加载的模块。可以像上面的代码那样手动操作,也可以使用
重新布线
模块。很公平:)谢谢!非常感谢你!这是出于良好实践的原因,还是Sinon不提供没有对象引用的存根?@lukas_o不确定我是否正确理解了你的问题。您可以像这样创建存根
const myStub=sinon.stub()
问题是告诉您的其余代码使用存根而不是原始函数。@YuryTarabanko谢谢,有时您的函数无法注入引用,因此您必须像在服务中那样包装myFunction。我错过了类似
var myFunction=sinon.stub('myFunction')
没有传递对象。@lukas_o但问题是
myFunction
是您的局部变量引用存根,而
myFuncton
在另一个模块中引用完全不同的函数。即使您有权访问引用,也不能更改引用(因为引用是按值传递的)。要做到这一点,您需要以某种方式“插入”加载的模块。可以像上面的代码那样手动操作,也可以使用
重新布线
模块。