Angular2(TypeScript)中的单元测试/模拟窗口属性 [英] Unit Testing/mocking Window properties in Angular2 (TypeScript)

查看:64
本文介绍了Angular2(TypeScript)中的单元测试/模拟窗口属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为Angular2中的服务构建一些单元测试.

I'm building some unit tests for a service in Angular2.

在我的服务中,我有以下代码:

Within my Service I have the following code:

var hash: string; hash = this.window.location.hash;

var hash: string; hash = this.window.location.hash;

但是,当我运行包含此代码的测试时,它将失败.

However when I run a test which contains this code, it will fail.

能够很好地利用Window的所有功能,但是当我使用PhantomJs时,我认为这是不可能的(我也尝试过Chrome产生相同的结果).

It'd be great to utilise all the features of Window, but as I'm using PhantomJs, I don't think this is possible (I have also tried Chrome which yields the same results).

在AngularJs中,我本来会模拟$ Window(或至少是有问题的属性),但是由于没有太多有关Angular2单元测试的文档,所以我不确定该怎么做.

In AngularJs, I would have resorted to mocking $Window (or at least the properties in question), but as there is not a lot of documentation for Angular2 unit testing I'm not sure how to do this.

任何人都可以帮忙吗?

Can anyone help?

推荐答案

在Angular 2中,您可以使用@Inject()函数通过使用字符串标记命名窗口对象来注入窗口对象,就像这样

In Angular 2 you can use the @Inject() function to inject the window object by naming it using a string token, like this

  constructor( @Inject('Window') private window: Window) { }

@NgModule中,您必须使用相同的字符串提供它:

In the @NgModule you must then provide it using the same string:

@NgModule({
    declarations: [ ... ],
    imports: [ ... ],
    providers: [ { provide: 'Window', useValue: window } ],
})
export class AppModule {
}

然后,您还可以使用令牌字符串来模拟它

Then you can also mock it using the token string

beforeEach(() => {
  let windowMock: Window = <any>{ };
  TestBed.configureTestingModule({
    providers: [
      ApiUriService,
      { provide: 'Window', useFactory: (() => { return windowMock; }) }
    ]
  });

这适用于Angular 2.1.1,它是2016年10月28日的最新版本.

This worked in Angular 2.1.1, the latest as of 2016-10-28.

不适用于Angular 4.0.0 AOT. https://github.com/angular/angular/issues/15640

Does not work with Angular 4.0.0 AOT. https://github.com/angular/angular/issues/15640

这篇关于Angular2(TypeScript)中的单元测试/模拟窗口属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆