Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Is there any way to mock this function with Jasmine or Sinon?

Is there any way to mock this function with Jasmine or Sinon?

Problem

I'm testing a module, and I want to mock out a a dependency within that module. Let me frame my scenario, if I may:

In my module

myModule.prototype.func = function(callback) {
    complexObj.doStuff('foo', function(err) {
        callback(err, 'stuff');
    });
};

So, I'm trying to basically mock complexObj. It doesn't really matter if I mock the entire object or just the doStuff function in this case. Let's assume that doStuff does something like interact with a web service or the filesystem. complexObj is being injected into myModule by dependency injection. I've been using Jasmine and Sinon to try to mock or stub this object and function, but I've had no luck, so I've resorted to something like this, which seems a little kludgy:

In my spec:

describe('Testing myModule', function() {
    it('should do stuff', function() {
        ComplexObj.prototype.doStuff = function(arg, callback) {
            callback(null); // If no errors, 'doStuff' returns null indicating no errors
        };

        var complexObj = new ComplexObj();

        new myModule(complexObj).func(function(err, results) {
            // Set up expectations...
        });
    });
});

So, as you can see, I'm psuedo-mocking out the doStuff function in the ComplexObj object. Since I'm not concerned about ComplexObj or doStuff function, I'm just invoking the callback with 'null' indicating to func that there were no errors in doStuff. As I mentioned before, I feel there should be a better way to handle this? Suggestions?

Problem courtesy of: naivedeveloper

Solution

With Jasmine, you would do something like this:

var complexObj = {doStuff: null};
spyOn(complexObj, 'doStuff');
new myModule(complexObj).func(function(err, results) {
    expect(complexObj.doStuff).toHaveBeenCalledWith(args, callback);
});

Edit: Or you could set up expectations in your mocked doStuff:

var complexObj = {doStuff: null};
spyOn(complexObj, 'doStuff').andCallFake(function(args, callback) {
    expect(args).toEqual(/*...*/);
    expect(callback).toEqual(/*...*/);
    callback();
});
new myModule(complexObj).func(function(err, results) {
    expect(complexObj.doStuff).toHaveBeenCalled();
});
Solution courtesy of: Linus Gustav Larsson Thiel

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Is there any way to mock this function with Jasmine or Sinon?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×