unit-testing – 如何在Angular2中对调用window.location.href的函数进行单元测试

我有这个功能我需要测试:

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

我使用window.location.href导航到外部URL.

这是我的测试:

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();
        })
    )
  );

当我运行此测试时,我收到以下错误

Some of your tests did a full page reload!

所以我试着模仿窗口对象

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

这没有改变,错误仍然存​​在.

有没有人有这个问题的解决方案?

解决方法

Window是一个无法注入的接口.你应该使用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;
  }
}

然后在测试中

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');
  }));
});

并记住配置app模块使用真正的窗口对象

@NgModule({
 declarations: [
    ...
  ],imports: [
    ...
  ],providers: [
    ...
    {provide: WindowToken,useFactory: _window},],bootstrap: [AppComponent]
})
export class AppModule {
}

相关文章

ANGULAR.JS:NG-SELECTANDNG-OPTIONSPS:其实看英文文档比看中...
AngularJS中使用Chart.js制折线图与饼图实例  Chart.js 是...
IE浏览器兼容性后续前言 继续尝试解决IE浏览器兼容性问题,...
Angular实现下拉菜单多选写这篇文章时,引用文章地址如下:h...
在AngularJS应用中集成科大讯飞语音输入功能前言 根据项目...
Angular数据更新不及时问题探讨前言 在修复控制角标正确变...