【问题标题】:Test if a component is passing an @Input to another测试一个组件是否将 @Input 传递给另一个
【发布时间】:2017-09-21 20:24:49
【问题描述】:

我对单元测试还很陌生。我想知道如何测试一个智能组件是否将一些作为 @Input() 传递给一个愚蠢的组件(使用 Angular 4+)。

一开始我想检查属性是否存在:

it('should have some data', async(() => {
  expect(component.data).toBeTruthy();
}));

但是,我遇到了两个问题:1)告诉我data 是否为真,但并不一定意味着它作为输入传递给我的哑组件; 2) 如果data 属性不存在,则不会执行测试套件。

有什么建议吗?有没有更好的方法来解决这个问题?谢谢。

【问题讨论】:

    标签: javascript angular unit-testing typescript


    【解决方案1】:

    由于输入绑定是作为更改检测的一部分处理的,因此您基本上可以更改父组件上绑定中使用的属性,然后在父组件上运行detectChanges() 并检查子组件中的输入属性是否已更改。大致如下:

    parentComponent = TestBed.createComponent(BannerComponent);
    const childComponentEl = fixture.debugElement.query(By.directive(ChildComponent));
    const childComponent = childComponentEl.injector.get(ChildComponent);
    
    it('should have some data', async(() => {
      parentComponent.componentInstance.boundProperty = 3;
      parentComponent.detectChanges();
      expect(childComponent.inputProperty).toBe(3);
    }));
    

    您可以阅读更多关于输入绑定更新原因的信息:

    【讨论】:

      猜你喜欢
      • 2019-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2017-06-10
      • 2019-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多