Wednesday, 17 May 2017

Mock require(ed) service

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.



via OscarRyz

No comments:

Post a Comment