Sinon意外的断言错误

我对Sinon的使用很新。

假设我们有模块(名为myModule.js)的定义:

//myModule.js var _f2 = function() { console.log('_f2 enter'); return {prop1:'var1'}; }; var f1 = function(){ var myVar1 = _f2(); console.log('_f2 called'); }; module.exports._f2 = _f2; module.exports.f1 = f1; 

这里是testing模块

 var sinon = require('sinon'); var myModule = require('./myModule'); describe('test my module',function(){ var f2Spy ; beforeEach(function(){ f2Spy = sinon.spy(myModule,'_f2'); }); afterEach(function(){ myModule._f2.restore(); }); it('call _f2',function(done){ myModule.f1(); sinon.assert.called(f2Spy); done(); }) }); 

运行这个testing时,我得到了assert错误:_f2没有被调用:

 AssertError: expected _f2 to have been called at least once but was never called 

但是从日志消息我可以看到_f2被调用。 问题是:什么原因导致错误? 提前致谢

如果你这样修改你的模块,那testing就会通过:

 var f1 = function(){ var myVar1 = exports._f2(); console.log('_f2 called'); }; 

(顺便说一句,在我上面的代码中使用exports相当于使用module.exports给出你已经显示的代码。)

原始代码的问题在于,其他常规JavaScript代码无法拦截在模块中进行的对_f2直接调用。 Sinon是普通的JavaScript代码,所以它不能拦截直接调用_f2 。 如果您通过exports表格打电话,那么Sinon有机会修补这张表格来拦截电话。