我有一个响应式表单,我将其拆分为更小的组件,以便能够更好地单独管理每个表单控件。我依靠事件发射器能够将每个控件的状态传达给管理整个表单状态的“父”组件。
我的给定组件的 ngOnInit 方法如下所示:
@Output() formReady: EventEmitter<FormControl> = new EventEmitter();
ngOnInit() {
(some other unrelated logic here...)
this.formReady.emit(this.userIdFormControl);
}
我尝试为该组件编写的测试非常简单
it('should emit formReady event when component is initialised', () => {
spyOn(component.formReady, 'emit');
expect(component.formReady.emit).toHaveBeenCalled();
});
然而,这个测试失败了,因为 Spy 永远不会被调用(尽管如果我向 ngOnInit 添加一个 clg 语句,我可以看到它被打印了预期的次数)。
我的问题是:是否可以在 ngOnInit 上调用 Spies?我不明白为什么它们不起作用,但你永远不知道!
提前致谢
蒂亚戈
最佳答案
问题是,OnInit
在 spy
创建之前被调用。
那是因为您可能在 beforEach
block 中调用了 fixture.detectChanges()
。只需删除它并在您的规范中调用它。
it('should emit formReady event when component is initialised', () => {
spyOn(component.formReady, 'emit');
fixture.detectChanges()
expect(component.formReady.emit).toHaveBeenCalled();
});
或者您可以在您的规范中再次调用 ngOnInit()
方法以查看它是否正常工作。
it('should emit formReady event when component is initialised', () => {
spyOn(component.formReady, 'emit');
component.ngOnInit();
expect(component.formReady.emit).toHaveBeenCalled();
});
关于Angular/Jasmine - 如果在 ngOnInit 上调用,Spies 是否工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54722798/