【问题标题】:Unexpected assertion error of SinonSinon的意外断言错误
【发布时间】:2014-04-12 08:37:39
【问题描述】:

我对诗乃的用法还很陌生。

假设我们有模块(名为 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; 

这是对模块的测试

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();
    })
});

运行此测试时,我收到断言错误,即未调用 _f2:

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

但从日志消息中我可以看到调用了 _f2。 问题是:错误的原因是什么?在此先感谢

【问题讨论】:

    标签: javascript node.js unit-testing sinon


    【解决方案1】:

    如果你以这种方式修改你的模块,那么测试将通过:

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

    (顺便说一句,在我上面的代码中使用exports 等同于在您显示的代码中使用module.exports。)

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

    【讨论】:

    • 感谢您快速而有帮助的回复
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    相关资源
    最近更新 更多