为什么西农认不出我的存根

Why doesn't sinon recognize my stub?

本文关键字:我的 存根 为什么      更新时间:2023-09-26

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

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

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

基于此

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

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

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

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

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