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

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

2 Comments

sadly I still get an injection error: NullInjectorError: R3InjectorError(DynamicTestModule)[InjectionToken WindowToken -> InjectionToken WindowToken]: NullInjectorError: No provider for InjectionToken WindowToken!
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.