Angular:单元测试未发出组件的输出

前端之家收集整理的这篇文章主要介绍了Angular:单元测试未发出组件的输出前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_404_4@
假设我有一个如下组件:

@Component({
  selector: 'example',template: ` `
})
export class ExampleComponent {
  value: any;
  @Output() output: EventEmitter<any> = new EventEmitter();

  onValueChange(newValue: any) {
    if (newValue !== this.value) {
      this.value = newValue;
      this.output.emit(newValue);
    }
  }
}

我写了一个类似下面的测试.我想测试一下,如果使用与value相同的值调用onValueChange,组件将不会输出重复值.是否存在单元测试的最佳实践,即永远不会调用可观察的订阅?虽然我在技术上的工作,但感觉有点hacky.

describe('ExampleComponent',() => {
  it('should not output duplicate values',() => {
    const component = new ExampleComponent();
    component.value = 1;
    component.output.subscribe(value => {
      // if the output is not triggered then we'll never reach this 
      // point and the test will pass
      expect(true).toEqual(false);
    });
    component.onValueChange(1);
  });
});
@H_404_4@

解决方法

你可以像这样使用间谍:

describe('ExampleComponent',() => {
    const component = new ExampleComponent();        
    spyOn(component.output,'emit');

    component.value = 1;
    component.onValueChange(1);

    expect(component.output.emit).not.toHaveBeenCalled();
  });
});
@H_404_4@ @H_404_4@

猜你在找的Angularjs相关文章