首页 > 解决方案 > 如何测试子组件的类属性?

问题描述

我正在寻找一种方法来测试子组件是否在测试组件中具有特定类。最好通过例子来展示它。

父组件是一个带有 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元素并确保每个元素都有一个键、一个工具提示和一个定义的类,该类必须等于EnglishKeyboardComponentgetFontClass()方法)中定义的字体类。

键和工具提示是 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 上添加了指向源文件的链接,您也可以浏览应用程序的源代码。

标签: angulartesting

解决方案


你可以检查nativeElement.classList

expect(appKey.nativeElement.classList.contains(component.getFontClass())).toEqual(true);

或者

expect(appKey.classes).toContain(component.getFontClass());

推荐阅读