Freewind
Freewind

Reputation: 198418

How to create a spy for jquery invocation `$(some)`?

I define a requirejs module to provide a function to get browser width:

browserTool.js

define(['jquery'], function($) {
    return {
        getBrowserWidth: function() {
            return $(window).width();
        }
    }
});

Now I want to write unit test for it, so I want to mock jquery:

define(['jquery', 'browserTool'], function(jquery, browserTool) {
   describe("test", function() {
      it("should do something", function() {
         spyOn(jquery, "apply").and.returnValue({
            width: function() { return 300; }
         }); 
         expect(browserTool.getBrowserWidth()).toEqual(300);
      });
   });
});

You can see I want to use: spyOn(jquery, "apply") to mock, but this test doesn't work, seems I spied on a wrong method.

How to fix it?

Upvotes: 0

Views: 278

Answers (1)

doldt
doldt

Reputation: 4506

You can't spy directly on jQuery selectors, because they return different object every time. A general Jasmine SpyOn trick when you can't get hold of a reference is to place the spy on the prototype. With jQuery it looks like this:

//spyOn $(window).width():
spyOn($.fn, 'width').

If you want to, you can extract the params from the arguments of the spy call (and see that ie. it was called on window).

As for apply: apply is a pure javascript method, not part of jQuery, so you can probably spy on it through the function prototype to which it belongs:

spyOn(Function.prototype, 'apply');

(I didn't try this code though)

Upvotes: 2

Related Questions