Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular unit testing window.location.href

login() {
  const endPoint = environment.myEndPoint;
  window.location.href = endPoint + '/myPath/login';
}

I am having angular service file with above code written in it to redirect to login URL. Now, I have written the below code in spec file to unit test it.

it('should call login method',() => {
  service.digitalssologin();
});

This test case sometimes covers the login method and executes successfully, while sometimes it fails and karma tool disconnects, so other test cases also stops executing. Is there any other way to write test case for this method?

Thanks in advance.

like image 285
Nikunj Mochi Avatar asked Sep 08 '26 16:09

Nikunj Mochi


1 Answers

You need to mock the window object for unit testing or else like you said, you will face this issue.

You need to do something like this for the project in the AppModule.

And then in your service, inject the window service in your constructor.

constructor(@Inject('Window') window: Window) {}
login() {
  const endPoint = environmment.myEndpoint;
  this.window.location.href = endpoint + '/myPath/login';
}
// mock the window object
let mockWindow = { location: { href: '' } };

TestBed.configureTestingModule({
  ...
  providers: [
    // provide the mock for 'Window' injection token.
    { provide: 'Window', useValue: mockWindow }
  ]
  ...
});

Once you mock the window object, you should not face the issue you are facing where the tests fail randomly.

like image 176
AliF50 Avatar answered Sep 11 '26 07:09

AliF50