javascript - How can i stub $(window).width() using Sinon? -


i have function in js view performs action if window width less 1000. i'm attempting write unit tests mocha, chai , running tests via karma test runner in phantom/chrome/chromium browser.

i use sinon stub methods , making return desired value. there condition check if window width less 1000 how can stub this, trying below,

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

but not working. there specific way can stub $(window).width() value?

sinon.stub() usage:

first: you're not passing methods/functions sinon.stub() correctly. here's correct way it:

sinon.stub(object, 'method'); 

where object object method want stub, 'method' string containing name of method.

another way overwrite current function stub, calling .stub() no arguments:

object.method = sinon.stub(); 

taking account, let's move on current code.

current code:

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

as wrote above - incorrect call sinon.stub().

putting aside, you're approaching wrong angle. cannot stub $(window).width() - $(window).width() isn't function, it's call function - returning number (here: width of window in px). that's value trying replace stub - arbitrary primitive (number), not bound variable.

next try:

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

now, why this wouldn't work?

we're stubbing width method on specific jquery object - but each call $(...) creates new one. here's 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/ )

solution

stub .width() method on prototype of jquery objects - methods/values available globally 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 can see, i've restored original .width() prototype method after using stub, in case have make use of later.)


Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -