Mock window.location.reload in Jasmine testing
Asked Answered
M

5

21

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?

Malia answered 4/12, 2014 at 23:33 Comment(1)
window.location.reload is not a writable property, so the browser won't let a spy override it. To get around this, see https://mcmap.net/q/275528/-jasmine-mock-window-objectSheridan
M
15

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(){});
Malia answered 8/12, 2014 at 23:19 Comment(1)
this function should be private. and then you don't test it. running in circles...Frivolity
C
2

You should always use $window instead of window.

Try this:

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

or just make your own:

$window = {location:{reload:function(){}}};
Chlamydeous answered 7/1, 2016 at 20:34 Comment(0)
C
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.

Cornuted answered 12/9, 2018 at 2:31 Comment(0)
A
-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');
});
Atory answered 30/3, 2017 at 10:44 Comment(0)
U
-3

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();
Urbai answered 21/1, 2020 at 10:22 Comment(1)
Cannot delete property 'location' of [object Window]...Creepie

© 2022 - 2024 — McMap. All rights reserved.