Sinon函数存根:如何在模块内调用"自己的"函数

als*_*kja 7 unit-testing node.js sinon

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

var myFunction = sinon.stub(nodeModule, 'myFunction');
myFunction.returns('mock answer');
Run Code Online (Sandbox Code Playgroud)

nodeModule是这样的

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

function myFunction() {

}

function anotherF() {
  myFunction();
}
Run Code Online (Sandbox Code Playgroud)

nodeModule.myFunction()模拟工作显然适用于类似的用例,但我想知道如何在调用时模拟另一个F()内的myFunction()调用nodeModule.anotherF()

Yur*_*nko 10

你可以稍微重构一下你的模块.像这样.

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

module.expors = service;

function myFunction(){};

function anotherFunction() {
   service.myFunction(); //calls whatever there is right now
}
Run Code Online (Sandbox Code Playgroud)

  • @lukas_o但问题是`myFunction`是引用存根的本地变量,而另一个模块中的`myFuncton`引用完全不同的函数.即使您有权访问它也无法更改引用(因为引用是按值传递的).要做到这一点,你需要以某种方式"装备"你加载的模块.手动如上面的代码或使用`rewire`模块. (2认同)