我正在 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/