Reputation: 2107
I would like to know if I can spy on the $ function in jQuery using Jasmine.
This is the code I want to test.
var Wrapper = Wrapper || {};
Wrapper.Controls = {};
/**
* Use an anonymous function to initialize all JavaScript
*/
(function($) {
Wrapper.Controls.Utils = function() {
var external = {
showHide : function(namespace, controlNameStem){
var stem = namespace + controlNameStem;
$(stem + 'Controller').click();
}
};
return external;
};
return Wrapper.Controls.Utils;
}(Wrapper.jQuery));
Wrapper.jQuery is in a separate file which is preloaded by Jasmine before loading Wrapper. It contains a stub jQuery which is defined like this
var aliasjQuery = {};
var Wrapper = Wrapper || {};
Wrapper.jQuery = aliasjQuery;
This means that when Wrapper is initialised, aliasjQuery is the object passed into the anonymous function as Wrapper.jQuery
My Jasmine test spec looks like this:
describe("form control utils", function(){
var controlUtils = Wrapper.Controls.Utils();
var namespace = 'pluto_namespace';
var controlName = 'dualNationality';
it("showHide fires click event on controlNameController", function(){
var control = { click : function(){}};
spyOn(aliasjQuery, '$').andReturn(control);
spyOn(control, 'click');
controlUtils.showHide(namespace, controlName);
expect(control.click).toHaveBeenCalled();
});
});
I welcome any comments, even those along the lines of "why on earth do you want to do that?" and alternative solutions as I think I've spent too long staring at this.
Upvotes: 1
Views: 1881
Reputation: 2107
Instead of this
var aliasjQuery = {};
I can create a spy function like so
var aliasjQuery = jasmine.createSpy();
and then have it return the control stub like this
aliasjQuery.and.returnValue(control);
so then I can do this
expect(aliasjQuery).toHaveBeenCalledWith('pluto_namespacedualNationality');
Upvotes: 0