How can I drown $ (window) .width () using Sinon?

I have a function in the JS view that performs some action if the window width is less than 1000. I am trying to write unit tests for this with Mocha, chai and run the tests through the karma test drive in the Phantom / Chrome / Chromium Browser.

I also use sinon to stub methods and make it return some desired value. Now there is a condition check where, if the window width is less than 1000, since I can drown it out, I tried something like below,

sinon.stub($(window).width()); $(window).width().returns(900); 

But it does not work. Is there any specific way in which I can drown out the $(window).width() value?

+5
source share
1 answer

sinon.stub() usage:

First: you are not passing methods / functions sinon.stub() to sinon.stub() . Here is the correct way to do this:

 sinon.stub(object, 'method'); 

Where object is the object whose method you want to stub, 'method' is a string containing the name of this method.

Another way is to simply overwrite the current function with a stub, calling .stub() with no arguments:

 object.method = sinon.stub(); 

Given this, go to your current code.

Current code:

 sinon.stub($(window).width()); 

As I wrote above, this is an incorrect call to sinon.stub() .

Putting it aside, you are approaching it from the wrong angle. You cannot drown $(window).width() - $(window).width() not a function, it is a function call - returning a number (here: window width in px). This value that you are actually trying to replace with a stub is an arbitrary primitive (number) that is not even associated with any variable.

Next attempt:

 sinon.stub($(window), 'width'); 

Now why this one didn't work?

We only handle the width method on this particular jQuery object, but each call to $(...) creates a new one. Here is the result:

 var $window = $(window); sinon.stub($window, 'width').returns(900); $window.width(); // 900 - using .width() method stub $(window).width(); // real window width - new jQuery object 

(jsfiddle: http://jsfiddle.net/xqco8u77/ )

Decision

Configure the .width() method on the prototype of jQuery objects whose methods / values ​​are available globally for each jQuery object.

 sinon.stub($.prototype, 'width').returns(900); // "900" $(window).width(); // restoring original function $.prototype.width.restore(); // real window width $(window).width(); 

Working demo on jsfiddle: http://jsfiddle.net/gjcguvzh/5/

(As you can see, I also restored the original prototype of the .width() method after using the stub, if you need to use it later.)

+7
source

All Articles