【问题标题】:How to unit test an angular @Output如何对角度@Output 进行单元测试
【发布时间】:2019-05-15 10:56:45
【问题描述】:

覆盖率报告中的问题:

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

}

component.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);
      });

    });
  });

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

如您所见,这不起作用,对如何对表单更改进行单元测试有任何帮助吗?

【问题讨论】:

  • 我认为您需要触发变更检测:在期望之前添加fixture.detectChanges()
  • 我试过@HodossySzabolcs :(
  • 那么我建议创建一个局部变量并订阅输出,您可以将变量设置为res,并对其进行测试。我做了类似的事情here。如果这还不够,您可以尝试使用TestHostComponent 描述here

标签: angular unit-testing karma-jasmine


【解决方案1】:

我认为您根本不需要whenStable,也不需要async。您应该使用detectChanges() 来触发更改检测。但这只能在实际开始之前完成,以触发ngOnInit 钩子(和朋友们)。

还可以使用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();
});

【讨论】:

    猜你喜欢
    • 2021-03-11
    • 2020-07-10
    • 1970-01-01
    • 2019-12-28
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    相关资源
    最近更新 更多