我有一个名为 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 覆盖层中,我如何检索它?
最佳答案
没有完整的代码很难提供帮助,但您可以做的只是通过 @ViewChild()
添加对 mat-select-controls
组件的引用在你的父组件中:
@ViewChild(MatSelectControls) matSelectControls: MatSelectControls;
然后在你的测试中使用它:
component.matSelectControls.abc
关于 Angular 单元测试 - 如何在覆盖容器中获取子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53935191/