0
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.

R. Richards
  • 23,283
  • 10
  • 63
  • 62
Nikunj Mochi
  • 11
  • 1
  • 3

1 Answers1

2

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.

AliF50
  • 13,496
  • 1
  • 15
  • 28