[英]Why doesn't sinon recognize my stub?
Let's say I have a module that exports like this:假设我有一个像这样导出的模块:
module.exports = mymodule;
Then in my test file, I require the module and stub it.然后在我的测试文件中,我需要该模块并存根它。
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();
}));
});
});
That works and the test passes!这有效并且测试通过了! But everything breaks down if I need to export more than one object.
但是如果我需要导出多个对象,一切都会崩溃。 See below:
见下文:
module.exports = {
api: getSports,
other: other
};
Then I try to adjust my test code:然后我尝试调整我的测试代码:
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();
}));
});
});
In this case, my test craps out.在这种情况下,我的测试失败了。 How can I change my stub code to work?
如何更改存根代码以使其正常工作? Thanks!
谢谢!
Based on this基于此
module.exports = {
api: getSports,
other: other
};
it looks like mymodule.api
doesn't itself have a getSports
method.看起来
mymodule.api
本身没有getSports
方法。 Rather, mymodyle.api
is a reference to a getSports
function insider your module.相反,
mymodyle.api
是对模块内部的getSports
函数的引用。
Instead of stubbing getSports
you would need to stub api
:而不是存根
getSports
你需要存根api
:
var getRequest = sinon.stub(mymodule, 'api');
However, given how you're trying to stub getSports
, you might instead want to update how you are exporting the function instead of how you are stubbing it.但是,考虑到您尝试存根
getSports
,您可能想要更新导出函数的方式,而不是存根它的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.