Reputation: 199215
I'm trying to mock a service used by my function using sinon, but I can't find a way to inject the mock into my function.
The service is acquired using require
My function is like this:
// 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;
});
}
}
I'm trying to mock service.foo
like this:
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});
});
And then check if my doSomething
method is indeed executing the logic it is supposed to execute.
Q. How do I inject a mock service and/or a mock function for that service that is defined as a private closure scoped variable in my something
function.
Upvotes: 0
Views: 184
Reputation: 199215
I end up using 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
}));
Upvotes: 0
Reputation: 1314
I believe you need to require service
in your test and stub it directly.
let service = require('../../service.js');
sinon.stub(service, 'foo' )
.returns(when(function() {
return ['bar', 'baz'];
}));
Upvotes: 1