我试图使用sinon来模拟我的函数使用的服务,但我无法找到一种方法将注入模拟到我的函数中。
使用require
我的功能是这样的:
// something.js
const service = require('./service');
module.exports = {
// do something using a service
doSomething: function (options) {
let results = [];
return service.foo(option.param)
// and return the value adding some logic
.then(function(resultFromService){
// want to test this flag
if ( options.someFlag ) {
results = resultFromService;
}
})
.then(function(){
/// more existing code here
return results;
});
}
}
我试图像这样嘲笑service.foo
:
const something = require('../../something.js');
const sinon = require('sinon');
...
it('should doSomething by calling foo in the service', function(done) {
///I'm getting this error here: Error: Trying to stub property 'foo' of undefined
sinon.stub( something.service , 'foo' )
.returns(when(function() {
return ['bar', 'baz'];
}));
let promise = something.doSomething({param:'for service', someFlag:true});
});
然后检查我的doSomething
方法是否确实正在执行它应该执行的逻辑。
Q值。如何为我的something
函数中定义为私有闭包范围变量的服务注入模拟服务和/或模拟函数。
答案 0 :(得分:1)
我认为您需要在测试中要求service
并直接存根。
let service = require('../../service.js');
sinon.stub(service, 'foo' )
.returns(when(function() {
return ['bar', 'baz'];
}));
答案 1 :(得分:0)
我最终使用mock-require
const mockRequire = require('mock-require');
it('do something', function(){
mockRequire('./service', {
foo: function(p){
return [];
}
});
let something = require('./something.js);
// Now when it requires the service, it gets the mock instead
something.doSomething({flag:true, param:'a'});
assert. etc. etc
}));