Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 如何对角度@输出进行单元测试_Angular_Unit Testing_Karma Jasmine - Fatal编程技术网

Angular 如何对角度@输出进行单元测试

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

报道中的问题是:

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

}
错误:什么都没有发生,我不知道如何对触发输出事件发射器的窗体进行单元测试


正如您所看到的,这不起作用,关于如何单元测试表单的任何帮助都会发生变化?

我认为您根本不需要在稳定时使用
,也不需要使用
异步
。您应该使用
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();
});