Some of your tests did a full page reload - error when running Jasmine tests

白昼怎懂夜的黑 提交于 2019-12-03 00:58:54

In my case the problem was that in my source code I had code directly setting the href on the location object, like window.location.href = 'somewhere';

In my specs I set up a onbeforeunload listener that just returns a string instead of allowing the redirect to take place:

beforeAll(() => {
  window.onbeforeunload = () => 'Oh no!';
});

Make sure that your tests are properly isolating all modules under test with mocks/spies. The behavior you are seeing says to me that your tests are not truly running in isolation - they are changing some state somewhere that will trigger a reload.

I suppose you are using window.location somewhere in your targeted code. In order to pass it just create a spy for the window.onbeforeunload

Example:

window.onbeforeunload = jasmine.createSpy();

Or even better use $window instead, and this will not happen.

I recently encountered this error with Karma 0.13.12. I upgraded to Karma 0.13.14 and my tests work again. The problem for me (and probably also for @mqklin) was related to https://github.com/karma-runner/karma/issues/1656 and https://github.com/jasmine/jasmine/issues/945.

Try to reduce amount of describe sections or completely remove them. I don't know why, but it works for me.

What worked for me was upgrading Karma from 1.4.0 to 1.4.1 and changing the maximumSpecCallbackDepth in my jasmine.js file from 20 to 100.

creating a spy on the function which has the window.location / reload fixed the issue for me

You also need to make sure that modules are not being loaded twice. In my case, I had an AngularJS module file -e.g., auth.controller.js which contents were already bundled in a core.js file. Once I excluded the bundled files on karma, the error disappeared.

I was using setTimeout(() => window.location.replace('/'), 10); I used below code in my unit test and it worked for me.

spyOn(global, 'setTimeout');

Hope you have used window.location = "some url" in your code; Faced similar problem, and solved by using the below changes.

Replaced window.location in the code with,

window.location.assign("some url");

Do the below in unit test:

spyOn(window.location, "assign").and.callFake(() => {
    // Dummy assign call - so that your actual call will be faked and the reload will not happen. 
});

In case it was ng-submit callback, which doesn't call "event.preventDefault()" and the browser reloads page. Mocking $location doesn't help in that situation.

It will solve this Karma redirect error!

var html = '<script type="text/javascript">';
html += 'window.location = "' + urlToRedirect +'"';
html += '</script>';
$( '.wrapper' ).append( html );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!