angular - 如何测试子组件的类属性?
问题描述
我正在寻找一种方法来测试子组件是否在测试组件中具有特定类。最好通过例子来展示它。
父组件是一个带有 HTML 摘录的键盘组件,如下所示,它以EnglishKeyboardComponent
相应的名称命名english-keyboard.component.html
(它包含国际音标英文音标的键;符号来自相应的类属性)。
...
<div class="col p-2">
<app-key [key]="'F'" [tooltip]="'(a)rrive'" class="{{getFontClass()}}"></app-key>
</div>
...
getFontClass()
返回用于英文键的类。
现在我想测试这些app-key
元素并确保每个元素都有一个键、一个工具提示和一个定义的类,该类必须等于EnglishKeyboardComponent
(getFontClass()
方法)中定义的字体类。
键和工具提示是 KeyComponent 的属性,我可以这样测试它,例如:
const appKeys = fixture.debugElement.queryAll(By.directive(KeyComponent));
for (const appKey of appKeys) {
expect(appKey.componentInstance.key).toBeTruthy();
expect(appKey.componentInstance.tooltip).toBeTruthy();
}
我不知道如何测试类属性。我对另一个组件进行了另一个测试,我可以测试类似的东西:
const buttonEl = fixture.nativeElement.querySelector('button');
expect(buttonEl.attributes.getNamedItem('title').value).toEqual('(c)ool');
这不适用于KeyComponent
,理想情况下我可以这样做:
expect(appKey.attributes.getNamedItem('class')).toEqual(component.getFontClass());
有人会碰巧知道一种方法来测试app-key
元素的类属性吗?
###更新###
我在 Github 上添加了指向源文件的链接,您也可以浏览应用程序的源代码。
解决方案
你可以检查nativeElement.classList
expect(appKey.nativeElement.classList.contains(component.getFontClass())).toEqual(true);
或者
expect(appKey.classes).toContain(component.getFontClass());
推荐阅读
- python - TypeError:无法将 cuda:0 设备类型张量转换为 numpy。使用 Tensor.cpu() 先将张量复制到主机内存(Segmentation using yolact edge)
- azure - Azure 发布管道在路径中找不到工件
- reactjs - 使用外部按钮控制 react-youtube 播放器
- python - 为什么当我显示 ROC 时,它显示我的第一类 ROC 是 nan?
- excel - 如何在Excel中获取彩色单元格的总和
- c - 如何在 C 和 C++ 中使用反斜杠作为分隔符?
- c# - 如何为 TextAsset 创建一个包装器并在 ScriptedImporter 中分配它?
- javascript - spawn 不是函数
- vim - 如何在执行 :Vexplore 并在新缓冲区中打开文件后自动关闭 netrw 窗格?
- powershell - Powershell从网页获取数据