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

1

7

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?

Circumbendibus answered 22/7, 2016 at 8:45 Comment(0)
D
5

Window is an interface and that cannot be injected. You should use OpaqueToken

import {Injectable, OpaqueToken, Inject} from '@angular/core';

export const WindowToken = new OpaqueToken('Window');
export const SomeServiceWithWindowDependencyToken = new OpaqueToken('SomeServiceWithWindowDependency');

export function _window(): Window {
  return window;
}


export class SomeServiceWithWindowDependency {
  private window: Window;

  constructor(@Inject(WindowToken) window: Window) {
    this.window = window;
  }
}

Then in tests

describe('SomeServiceWithWindowDependency', () => {
  beforeEach(() => {
    let mockWindow: any = {
      location: {
        hostname: ''
      }
    };
    TestBed.configureTestingModule({
      providers: [
        {provide: WindowToken, useValue: mockWindow},
        {provide: SomeServiceWithWindowDependencyToken, useClass: SomeServiceWithWindowDependency}
      ]
    });
  });
  it('should do something', inject([SomeServiceWithWindowDependencyToken, WindowToken], (tested: SomeServiceWithWindowDependency, window: Window) => {
    window.location.hostname = 'localhost';
    expect(tested.someMethod()).toBe('result');
  }));
});

And remember to configure app module to use real window object

@NgModule({
 declarations: [
    ...
  ],
  imports: [
    ...
  ],
  providers: [
    ...
    {provide: WindowToken, useFactory: _window},
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}
Distrustful answered 19/10, 2016 at 22:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.