angular - 如何为 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);
}
}
解决方案
我不会费心测试材料芯片,因为材料组件有自己的测试。无需测试框架。
相反,我认为您应该测试操纵绑定到芯片的数据的方法(添加、删除等)
这将使测试变得更加简单,因为您的测试不需要支持 Angular。
如果您的 Component 不能被实例化并且在不涉及框架的情况下调用这些方法,我会将这些方法提取到另一个可以的类中,也许是一个服务。
推荐阅读
- c# - 如何在 PdfWriter 中应用自定义字体系列 iTextSharp(HTML 到 PDF)?
- java - 如何对 gradle 项目中某个类型的所有文件运行 java 方法?
- c - 为什么来自 main 的 Pthread Signal 会挂起代码?
- node.js - 使用 jimp 将项目推送到数组的“文件意外结束”
- java - 尺寸比较(周长/平方周长)等
- angular - 将数据发送到 TemplateRef MatDialog
- reactjs - 创建反应应用程序时获取包失败
- c - If then 有多个表达式 OCaml
- angular - rxjs-marbles 测试没有任何期望
- python - 限制输入 SQLite3 的字符数