Sinon函数存根:如何调用"拥有"模块内部的功能

时间:2016-02-02 19:54:21

标签: 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 anotherF() {
  myFunction();
}

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

1 个答案:

答案 0 :(得分:9)

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

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

module.expors = service;

function myFunction(){};

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