Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock window.location.reload in Jasmine testing

I have created a window.location.reload function in my javascript.

I need to mock the reload function while testing in Jasmine since it keeps on looping.

The test goes well when I run grunt jenkins. But not while testing in the browser (mozilla/chrome).

Here is my code snippet.

Javascript:

window.location.reload();

Jasmine Test:

spyOn(window.location, 'reload').and.callFake(function(){});

Can anyone please help me on this?

like image 708
Viji Pandithurai Avatar asked Dec 04 '14 23:12

Viji Pandithurai


2 Answers

Thanks for sharing your views.

I did a work around as suggested and it was successful.

Since window is a browser object and cannot be spied upon, I just wrapped the function in JavaScript and referred that function in my test spec.

Javascript code:

var function = windowReload(){
    window.location.reload();
}

call the function windowReload() where required.

Jasmine Test:

spyOn(obj, 'windowReload').andCallFake(function(){});
like image 166
Viji Pandithurai Avatar answered Oct 17 '22 00:10

Viji Pandithurai


You should always use $window instead of window.

Try this:

$window = jasmine.createSpy('$window');

or just make your own:

$window = {location:{reload:function(){}}};
like image 2
mkaj Avatar answered Oct 17 '22 02:10

mkaj