Mock window.location.reload in Jasmine testing

落花浮王杯 提交于 2019-12-22 01:54:26

问题


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?


回答1:


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(){});



回答2:


You should always use $window instead of window.

Try this:

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

or just make your own:

$window = {location:{reload:function(){}}};



回答3:


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.




回答4:


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');
});


来源:https://stackoverflow.com/questions/27306194/mock-window-location-reload-in-jasmine-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!