Thomas Desmond Headshot
Thomas Desmond
Sitecore Developer Advocate
Last Updated:

Stubbing location.reload in Angular for Jasmine Tests

I encountered a peculiar problem where my Jasmine unit tests were running FOREVER. Every time the tests finished, they just kept running again and again. I reached 1505 out of 490 unit tests run.

I found the culprit, thanks to small commits, and it was a location.reload() call in my production Angular code.

Let's look at the two steps to stub out location.reload() for testing. Note: I did not want/need to test my location.reload(), I just wanted to get past it, essentially ignore it.

Step One

First off, we need to move our location.reload() call, from our production code, into its own function. We do this because it makes it MUCH easier for us to stub out a component level function in our test. So here we made a simple reloadPage function.

1  reloadPage() {
2    location.reload();
3  }

Step Two

Next up, we go to our tests. I am assuming you already have your tests set up, most importantly getting an instance of your component under test. We can now reassign our reloadPage function to an empty function.

1  it('should do the thing we want', () => {
2    component.reloadPage = function() { };
3    // Rest of our test goes here
4    
5  });

In the above code, we are stubbing out or overriding the function reloadPage from our component. In this test, reloadPage no longer calls location.reload(). It will call our empty function instead, thus doing nothing. We have essentially removed the location.reload() call from this test or more appropriately stubbed reloadPage out.

Again Note: In my situation, I did not want/need to test location.reload() with this test. I simply wanted to get past it, essentially ignore it.

After making these changes, the tests ran as expected. No more 1505 out of 490 tests. I hope this helped and if it did leave a comment!

For more interesting JavaScript related posts check out const in JavaScript is weird! The non-immutable const.