5
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
  • 24,603
  • 10
  • 64
  • 64
Nikunj Mochi
  • 61
  • 1
  • 1
  • 4

1 Answers1

7

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
  • 16,947
  • 1
  • 21
  • 37
  • 1
    sadly I still get an injection error: NullInjectorError: R3InjectorError(DynamicTestModule)[InjectionToken WindowToken -> InjectionToken WindowToken]: NullInjectorError: No provider for InjectionToken WindowToken! – Royer Adames Oct 12 '22 at 16:55
  • 1
    and that was because I was using a custom injection token. All I needed to do was use that token in the mock and now the error is gone – Royer Adames Oct 12 '22 at 17:17