假设我有一个类似以下内容的组件:

@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);
    }
  }
}
我已经写了一个类似下面的测试。我想测试是否以与onValueChange相同的值调用value,该组件将不会输出重复的值。有没有关于单元测试的最佳实践,即从不调用可观察的订阅?从技术上讲,我的工作原理不错,但感觉有些古怪。
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);
  });
});

最佳答案

您可以使用这样的 spy :

describe('ExampleComponent', () => {
  it('should not output duplicate values', () => {
    const component = new ExampleComponent();
    spyOn(component.output, 'emit');

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

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

关于 Angular :单元测试,不输出组件的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46817783/

10-09 17:35
查看更多