加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:43:20 所属栏目:安全 来源:网络整理
导读:假设我有一个如下组件: @Component({ selector: 'example',template: ` `})export class ExampleComponent { value: any; @Output() output: EventEmitterany = new EventEmitter(); onValueChange(newValue: any) { if (newValue !== this.value) { this.v
假设我有一个如下组件:

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

解决方法

你可以像这样使用间谍:

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读