如何编写角材料芯片的单元测试?

时间:2020-05-16 22:58:11

标签: angular angular-material

我正在使用输入为here的芯片

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

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

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);
    }
  }

Link to stackblitz

2 个答案:

答案 0 :(得分:1)

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

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

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

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

答案 1 :(得分:0)

我也被这个问题困住了,因为我还在学习 angular。 我阅读了其他几个类似的 stackoverflow 问题,其中包含我所需要的一些零碎内容,但不是这个问题的解决方案。

您的问题的答案分为两部分。

  1. 要添加,您需要获取输入字段的 nativeElement。这样您就可以在添加事件中将其用作 MatChipInputEvent。

你可以给你的输入添加一个id,这样你就可以拉入nativeElement:

<input placeholder="New fruit..."
    [id]="input-fruit-id"
    [matChipInputFor]="chipList"
    [matChipInputSeparatorKeyCodes]="separatorKeysCodes"
    [matChipInputAddOnBlur]="addOnBlur"
    (matChipInputTokenEnd)="add($event)"
>

接下来在测试中,您需要添加以下代码以获取 nativeElement 并在您的函数中使用它。

const inputElement: HTMLElement = fixture.debugElement.query(
    By.css('#input-fruit-id')
).nativeElement;
component.add({
    input: inputElement,
    value: <put a test value here, for example: 'orange'>,
} as MatChipInputEvent);
fixture.detectChanges();

接下来检查您的水果列表,看看是否添加了价值。

  1. 这部分是 GreyBeardedGeek 提到的。您只需要测试您的功能而不是 MatChip。以下是我将如何测试删除:
const fruitList = [ 'orange', 'apple', 'peach' ];
component.fruits = fruitList;
       
component.remove('orange');
fixture.DetectChanges();

现在检查“orange”是否已从列表中删除。

相关问题