Friday 31 January 2014

stubbing awkward jquery calls with sinon.js

We had an awkward bit of code at work the other day that called a third party control  like so:

function myObject(jsSelector) {
    return $(jsSelector).thirdpartycall({
            propertya: valuea,
            propertyb: valueb
    });
};



so if we want to test myObject, we are now stuck with the unfortunate jquery call inside.  not to worry, sinon.js to the rescue.  first i need to create a fake return object from that javascript call:

 var fakeResult = {
        propertya,
        propertyb,
        thirdpartycall: function (values) {
            this.propertya = values.propertya;
            this.propertyb = values.propertyb;
            return true;
        }
    };

what i do next is to stub jquery, and on using the selector it returns our fake object... yep how cool is that !
make sure when you write your test you wrap it like so (i had some fun with other tests failing after this as I had stubbed jquery permanently !!!)

it("should do something....", sinon.test(function () {

}));

then add the code:

it("should do something....", sinon.test(function () {
    $ = this.stub();
    $.withArgs('#myselector').returns(fakeResult);
}));
           
so now, if we call our object:

myObject('#myselector');

we then check fakeResult and the properties have been set.
Super awesome.