为什么 sinon 不识别我的存根?
Why doesn't sinon recognize my stub?
假设我有一个像这样导出的模块:
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
函数的引用。
您需要存根 api
,而不是存根 getSports
:
var getRequest = sinon.stub(mymodule, 'api');
但是,考虑到您尝试存根的方式 getSports
,您可能想要更新导出函数的方式而不是存根方式。
假设我有一个像这样导出的模块:
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
函数的引用。
您需要存根 api
,而不是存根 getSports
:
var getRequest = sinon.stub(mymodule, 'api');
但是,考虑到您尝试存根的方式 getSports
,您可能想要更新导出函数的方式而不是存根方式。