【问题标题】:Why doesn't sinon recognize my stub?为什么诗乃不认识我的存根?
【发布时间】:2016-04-23 01:07:23
【问题描述】:

假设我有一个这样导出的模块:

module.exports = mymodule;

然后在我的测试文件中,我需要模块并存根它。

var mymodule = require('./mymodule');

describe('Job gets sports data from API', function(){

    context('When there is a GET request', function(){
        it('will call callback after getting response', sinon.test(function(done){
            var getRequest = sinon.stub(mymodule, 'getSports');
            getRequest.yields();
            var callback = sinon.spy();
            mymodule.getSports(callback);
            sinon.assert.calledOnce(callback);
            done();
        }));
    });
});

这行得通,测试通过了!但是如果我需要导出多个对象,一切都会崩溃。见下文:

module.exports = {
    api: getSports,
    other: other
};

然后我尝试调整我的测试代码:

var mymodule = require('./mymodule');

describe('Job gets sports data from API', function(){

    context('When there is a GET request', function(){
        it('will call callback after getting response', sinon.test(function(done){
            var getRequest = sinon.stub(mymodule.api, 'getSports');
            getRequest.yields();
            var callback = sinon.spy();
            mymodule.api.getSports(callback);
            sinon.assert.calledOnce(callback);
            done();
        }));
    });
});

在这种情况下,我的测试失败了。如何更改我的存根代码才能工作?谢谢!

【问题讨论】:

    标签: javascript node.js mocha.js sinon


    【解决方案1】:

    基于此

    module.exports = {
        api: getSports,
        other: other
    };
    

    看起来mymodule.api 本身没有getSports 方法。相反,mymodyle.api 是对模块内部的 getSports 函数的引用。

    您需要存根api,而不是存根getSports

    var getRequest = sinon.stub(mymodule, 'api');
    

    但是,鉴于您尝试存根 getSports 的方式,您可能希望更新导出函数的方式而不是存根函数的方式。

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 1970-01-01
      • 2019-07-07
      • 2017-05-12
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      相关资源
      最近更新 更多