vendredi 22 juillet 2016

How to unit-test a function that calls window.location.href in Angular2

I have this function I need to test:

login(): void {
    this.userService.setSessionAndDateOnlogin();
    this.loginService.getLogin()
      .subscribe(
        octopusUrl => window.location.href = octopusUrl);
  }

I use the window.location.href to navigate to an external URL.

This is my test:

it('login function should call the setSessionAndDateOnLogin function from the userservice and\
   subscribe to the  getLogin function of the loginService.',
    fakeAsync(
      inject(
        [LoginComponent, LoginService, UserService],
        (loginComponent: LoginComponent, loginService: LoginService, userService: UserService) => {
          spyOn(userService, 'setSessionAndDateOnlogin');
          loginComponent.login();
          expect(userService.setSessionAndDateOnlogin).toHaveBeenCalled();
        })
    )
  );

When I run this test, I get the following error:

Some of your tests did a full page reload!

So I tried to mock the window-object:

import { window } from '@angular/platform-browser/src/facade/browser';
...
class MockWindow {
  location: {
    href: ''
  };
}
...
beforeEach(() => addProviders([
    ...
    { provide: window, useClass: MockWindow }
  ]));

This changed nothing and the error remains.

Does anyone has a solution for this issue?

Aucun commentaire:

Enregistrer un commentaire