admin管理员组文章数量:1323707
I'm trying to test code using Sinon.js, but I'm unfamiliar with out it's supposed to behave.
I expect that I can create a 'fake' object, wrap it with sinon and pass it to whatever I'm testing, and have it do its thing. However, it seems like every time I try to wrap a sinon object, the function is not there:
var event_api = {
startTime: function() {
return '123';
}
}
var stub = sinon.stub(event_api);
console.log(stub.startTime()) // returns undefined
var mock = sinon.mock(event_api);
console.log(mock.startTime()) // returns undefined
What am I missing?
I'm trying to test code using Sinon.js, but I'm unfamiliar with out it's supposed to behave.
I expect that I can create a 'fake' object, wrap it with sinon and pass it to whatever I'm testing, and have it do its thing. However, it seems like every time I try to wrap a sinon object, the function is not there:
var event_api = {
startTime: function() {
return '123';
}
}
var stub = sinon.stub(event_api);
console.log(stub.startTime()) // returns undefined
var mock = sinon.mock(event_api);
console.log(mock.startTime()) // returns undefined
What am I missing?
Share Improve this question asked Jan 8, 2014 at 3:59 JamesJames 6,50911 gold badges61 silver badges87 bronze badges2 Answers
Reset to default 5It depends on what are you trying to do:
If you don't have any expectations on the call then you should use a stub, for example startTime() only has to return a value.
var event_api = {
startTime: sinon.stub().returns('123')
}
console.log(event_api.startTime());
But if what you want is to set some assertions for the call, then you should use a mock.
var event_api = {
startTime: function() {
return '123';
}
}
//code to test
function getStartTime(e) {
return e.startTime();
}
var mock = sinon.mock(event_api);
mock.expects("startTime").once();
getStartTime(event_api);
mock.verify();
Hope this helps.
The function is indeed there, but it's void of any functionality, since it has been stubbed. If you want to log the function itself in the console, you have to execute:
console.log(stub.startTime) //logs the function itself
instead of:
console.log(stub.startTime()) //logs the result of the function, which is undefined
However, as said, all the methods of a stub object have been "emptied" of their functionality. If you want to make a method of a stubbed object return a value, you can do the following:
var stub = sinon.stub(event_api);
stub.startTime.returns(123);
console.log(stub.startTime) //log the function
console.log(stub.startTime()) //log the result of function, that is now 123
本文标签: javascriptCreating test objects in SinonjsStack Overflow
版权声明:本文标题:javascript - Creating test objects in Sinon.js - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742129532a2422094.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论