Angular 如何对角度@输出进行单元测试
报道中的问题是: 我在components.ts中有这个代码Angular 如何对角度@输出进行单元测试,angular,unit-testing,karma-jasmine,Angular,Unit Testing,Karma Jasmine,报道中的问题是: 我在components.ts中有这个代码 export class TimelinePlotComponent implements OnInit, OnChanges, OnDestroy { form: FormGroup; @Output() onchange: EventEmitter<any> = new EventEmitter<any>(); constructor() {} initForm() { this.form
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);
});
}
}
错误:什么都没有发生,我不知道如何对触发输出事件发射器的窗体进行单元测试
正如您所看到的,这不起作用,关于如何单元测试表单的任何帮助都会发生变化?我认为您根本不需要在稳定时使用
,也不需要使用异步。您应该使用detectChanges()
触发更改检测。但这只能在实际启动之前完成,以触发ngOnInit
hook(和朋友)
同时使用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();
});
我认为您需要触发更改检测:在预期之前添加fixture.detectChanges()
。我已经尝试了@HodossySzabolcs:(然后我建议创建一个局部变量并订阅输出,您可以将该变量设置为res
,然后进行测试。我会做类似的操作。如果这还不够,您可以尝试使用所述的TestHostComponent
)
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();
});