20

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?

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Viji Pandithurai
  • 349
  • 1
  • 2
  • 6
  • 3
    `window.location.reload` is not a writable property, so the browser won't let a spy override it. To get around this, see http://stackoverflow.com/questions/8919370/jasmine-mock-window-object – user2943490 Dec 05 '14 at 12:14

5 Answers5

14

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(){});
Andrei T
  • 511
  • 1
  • 10
  • 16
Viji Pandithurai
  • 349
  • 1
  • 2
  • 6
2

You should always use $window instead of window.

Try this:

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

or just make your own:

$window = {location:{reload:function(){}}};
mkaj
  • 3,421
  • 1
  • 31
  • 23
0

I just meet the same issue. window.location = '' cause inf loop while run in browser. A simple solution is set window.location = '#' to stop reload.

wanana
  • 361
  • 1
  • 9
-2

This worked for me in BeforeEach with Jamine

delete window.location;
window.location = Object.create(window);
window.location.reload = () => {};
spyOn(window.location, 'reload');

and this worked using Jest

delete window.location;
window.location = Object.create(window);
window.location.reload = jest.fn();
AngularBoy
  • 1,715
  • 2
  • 25
  • 35
-3

You can always do:

beforeAll(() => {
  window.reload = () => console.log('Mock redirect');
});

Respectively:

beforeAll(() => {
  window.onbeforeunload = () => console.log('Mock redirect');
  window.open = () => console.log('Mock redirect');
});
Olezt
  • 1,638
  • 1
  • 15
  • 31