Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
stijn.aerts Avatar asked Jul 22 '16 08:07

stijn.aerts


1 Answers

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 {
}
like image 184
Mikołaj Grząślewicz Avatar answered Oct 07 '22 12:10

Mikołaj Grząślewicz