angular - 测试 Angular 组件时 NgZone 未定义

标签 angular unit-testing

我正在 Angular 中开发一个日期范围选择器组件,并且很难测试输入值是否错误。

我的 ngOnInit() 执行了 check for min/max date values .

当我尝试写 test for this case

Jasmine 归来:

Expected function to throw RangeError, but it threw TypeError: Cannot read property 'ngZone' of undefined.

研究 S.O.帖子,引导我创建了一个 mock NgZone class并在 TestBed 中提供它,这只会导致更多问题,例如“订阅未定义”。

我认为这可能是由于 EventEmitter 造成的,但我尝试删除它,但收到了相同的错误。

首先,如何解决 NgZone 错误?有几个S.O.关于这个主题的帖子,但我似乎还不够。

其次,如果传入错误的值,如何正确测试我的 ngOnInit() 的行为是否符合预期?

更新

即使我隔离了输入验证函数,我仍然无法检查该函数是否抛出错误。相反,我必须检查 detectChanges(),这是调用其他所有内容的函数:

expect(() => fixture.detectChanges()).toThrow();

最佳答案

NgZone服务用于访问 Api,以支持在 ZoneJS 空间内部和外部运行代码。但是,如果您发现在测试中使用它很有用,您可以使用以下方法创建该服务的实例:

let ngService = Testbed.get(NgZone)

如果您的目的是测试组件的生命周期 ngOnInit(),Angular 在 Testbed 中为此提供了工具。通过使用 ComponentFixture 的 API,您可以控制生成更改检测以触发 ngOnInit,如下所示:

describe('tests', () => {

  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
        imports: [ ],
        declarations: [ MyComponent ],
    }).compileComponents();
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;

  }));


  it('simple test', async(() => {
    fixture.detectChanges(); // triggers cd and passes through component lifecycle ngOnInit

  }));

});

关于angular - 测试 Angular 组件时 NgZone 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53292151/

相关文章:

angular - 调用服务 angular2 错误 'Property ' 然后'在类型 'Subscription' 上不存在

python - 你能用我的具体例子解释测试驱动开发吗?

c# - Service Fabric 单元测试和依赖项注入(inject)

java - PowerMockito thenReturn 返回错误的对象

angular - 有没有办法在 Angular 5 中轻松包装或扩展 Angular-material 指令?

html - 在 typescript 中带有 foreach 的模板电子邮件 html

javascript - 对复杂数据元素的引用

带有 @nguniversal 的 Angular SSR 和用于 PostCSS 支持的自定义 webpack

c++ - 如何防止eclipse c/c++单元测试遇到XML解析错误导致runner挂起?

unit-testing - 在 MSTest 中,如何使用 [ExpectedException(typeof(ApplicationException))] 验证确切的错误消息