首页 > 解决方案 > 如何为 Angular 材料芯片编写单元测试?

问题描述

我在这里使用带有输入的芯片

如何为添加和删除功能编写单元测试?

在删除的情况下,我们可以使用数组和字符串进行模拟,但是如何测试删除功能。

HTML

<mat-form-field class="example-chip-list">
  <mat-chip-list #chipList aria-label="Fruit selection">
    <mat-chip *ngFor="let fruit of fruits" [selectable]="selectable"
             [removable]="removable" (removed)="remove(fruit)">
      {{fruit.name}}
      <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>
    <input placeholder="New fruit..."
           [matChipInputFor]="chipList"
           [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
           [matChipInputAddOnBlur]="addOnBlur"
           (matChipInputTokenEnd)="add($event)">
  </mat-chip-list>
</mat-form-field>

TS

  add(event: MatChipInputEvent): void {
    const input = event.input;
    const value = event.value;

    // Add our fruit
    if ((value || '').trim()) {
      this.fruits.push({name: value.trim()});
    }

    // Reset the input value
    if (input) {
      input.value = '';
    }
  }

  remove(fruit: Fruit): void {
    const index = this.fruits.indexOf(fruit);

    if (index >= 0) {
      this.fruits.splice(index, 1);
    }
  }

链接到 stackblitz

标签: angularangular-material

解决方案


我不会费心测试材料芯片,因为材料组件有自己的测试。无需测试框架。

相反,我认为您应该测试操纵绑定到芯片的数据的方法(添加、删除等)

这将使测试变得更加简单,因为您的测试不需要支持 Angular。

如果您的 Component 不能被实例化并且在不涉及框架的情况下调用这些方法,我会将这些方法提取到另一个可以的类中,也许是一个服务。


推荐阅读