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

时间:2017-10-18 19:28:06

标签: angular jasmine rxjs

让我们说我有一个如下组件:

@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相同的值,组件将不会输出重复值。是否存在单元测试的最佳实践,即永远不会调用可观察的订阅?虽然我在技术上的工作,但感觉有点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);
  });
});

2 个答案:

答案 0 :(得分:6)

你可以使用这样的间谍:

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();
  });
});

答案 1 :(得分:1)

这就是你如何做到的。一个变化是:

describe('ExampleComponent', () => {
  it('should not output duplicate values', () => {
    const component = new ExampleComponent();
    let numEvents = 0;
    component.value = 1;
    component.output.subscribe(value => ++numEvents);
    component.onValueChange(1);
    expect(numEvents).toEqual(0);
  });
});