Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test window.location.reload in angular 12 unit testing?

In my angular project, I have a function

reloadPage(): void {
  window.location.reload();
}

So when ever I need to reload the page, I used to call this function.

Now I am trying to add the unit testing for this function but it is not working.

it("reloadPage: should be validated", () => {
    spyOn(window.location, 'reload').and.callFake(() => {
      //test
    });
    component.reloadPage();
});

It still reloads the page on unit testing

How can I achieve a unit test for this function? Any help could be appreciated. Thanks in advance

like image 830
Arun Avatar asked Jun 21 '26 17:06

Arun


1 Answers

You have to provide mock Window object in your TestBed.configureTestingModule

First create a window token

import { InjectionToken } from '@angular/core';

export const WINDOW = new InjectionToken('Window');

Create a mock object

windowMock = {
location: {
reload: jasmine.createSpy('reload')
 }
}

And then in providers

{provide: WINDOW, useValue: windowMock}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!