【问题标题】:Angular unit testing - How can I get the child component inside an overlay container角度单元测试 - 如何在覆盖容器中获取子组件
【发布时间】:2019-05-24 21:38:02
【问题描述】:

我有一个名为 MatSelectControls 的自定义组件,其用法如下:

<component-im-testing>
   <mat-select>
      <mat-select-controls></mat-select-controls>
      <mat-option *ngFor="..."></mat-option>
   </mat-select>
</component-im-testing>

在我的测试中,我可以像这样检索MatSelect 实例:

const matSelectRef = fixture.debugElement.query(By.directive(MatSelect));
const matSelect = matSelectRef.componentInstance as MatSelect;
matSelect.open();

但我真正追求的是MatSelectControls 组件。尝试以相同的方式选择它不起作用:

const matControlsRef = fixture.debugElement.query(By.directive(MatSelectControls)); //returns null

我假设这不起作用,因为 MatSelectControls 实际上呈现在 MatSelect 创建的 cdk 覆盖层内。

即使MatSelectControls 组件实例实际上呈现在 cdk 覆盖层内,我如何才能检索它?

【问题讨论】:

    标签: angular angular-material2 angular-test


    【解决方案1】:

    如果没有完整的代码,很难提供帮助,但您可以做的只是在父组件中通过 @ViewChild() 添加对 mat-select-controls 组件的引用:

    @ViewChild(MatSelectControls) matSelectControls: MatSelectControls;
    

    然后在你的测试中使用它:

    component.matSelectControls.abc
    

    【讨论】:

    • 我的问题是:我怎么知道 matSelectControls 被定义的那一刻
    • 类似fixture.detectChanges(); fixture.whenStable().then(() =&gt; { /* code here */ }.
    猜你喜欢
    • 2021-05-21
    • 2021-03-29
    • 2020-05-12
    • 2020-06-05
    • 1970-01-01
    • 2020-02-21
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    相关资源
    最近更新 更多