作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我在 components.ts 中有这段代码
export class TimelinePlotComponent implements OnInit, OnChanges, OnDestroy {
form: FormGroup;
@Output() onchange: EventEmitter<any> = new EventEmitter<any>();
constructor() {}
initForm() {
this.form = new FormGroup({
timeRange: new FormControl(this.time_range_options_active, []),
metric: new FormControl(this.metric_options_active, []),
groupBy: new FormControl(this.group_by_options_active, []),
});
// How to unit test this part of the code
this.form.valueChanges.subscribe( res => {
console.log('form-changed');
this.onchange.emit(res);
});
}
}
fit('should listen for form changes', async() => {
component.form.controls['groupBy'].setValue('color');
fixture.detectChanges();
fixture.whenStable().then(() => {
// your expectations.
expect(component.form.valid).toBeTruthy();
component.onchange.subscribe( res => {
console.log('res: ', res);
});
});
});
error: nothing is happening, I dont know how to unit test a form that triggers an output event emitter.
如您所见,这不起作用,关于如何对表单更改进行单元测试有什么帮助吗?
最佳答案
我认为您根本不需要 whenStable
,而且 async
也不是必需的。您应该使用 detectChanges()
来触发变化检测。但这应该只在实际开始之前完成,以触发 ngOnInit
Hook (和 friend )。
同时使用 spy
来确保输出已被调用:
fit('should listen for form changes', () => {
spyOn(component.onchange, 'emit');
fixture.detectChanges();
component.form.controls['groupBy'].setValue('color');
expect(component.form.valid).toBeTruthy();
expect(component.onchange.emit).toHaveBeenCalled();
});
关于angular - 如何对 Angular @Output 进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53775176/
我是一名优秀的程序员,十分优秀!