gpt4 book ai didi

angular - 如何对 Angular @Output 进行单元测试

转载 作者:太空狗 更新时间:2023-10-29 17:49:09 27 4
gpt4 key购买 nike

覆盖率报告中的问题: enter image description here

我在 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);
});
}

}

组件.spec.ts

  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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com