[英]How to mock a function defined with this keyword using sinon?
我有一个功能foo
var foo = function(){
this.doRandomStuff = function(callback){
//do Something
callback(false);
}
}
var bar = function(){
var fooInstance = new foo();
fooInstance.doRandomStuff(function(val){
//do Something with val
})
}
我想为bar功能编写测试,为此我正在使用mocha和sinon。
describe("Foo Test",function(){
it("testing foo",function(done){
var instance = new foo();
sinon.stub(instance,'doRandomStuff').callsArgWith(0,true); // This Doesn't work
sinon.stub(foo,'doRandomStuff').callsArgWith(0,true); // This also Doesn't work
bar();
done();
})
});
我得到以下异常:
TypeError:无法存根不存在的自己的属性doRandomStuff
使其更易于测试的替代方法是模块方法,如下所示:
foo.js
function doRandomStuff(callback) {
callback(false);
}
module.exports = {
doRandomStuff
}
bar.js
const foo = require('./foo');
module.exports = function() {
foo.doRandomStuff(function(val) {
console.log('test val', val); // for testing purpose
})
}
test.js
const sinon = require('sinon');
const foo = require('./foo');
const bar = require('./bar');
describe('Foo Test', function() {
it("testing foo",function(done){
sinon.stub(foo, 'doRandomStuff').callsArgWith(0,true);
bar(); // output: "test val true"
done();
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.