【发布时间】:2021-08-13 08:20:42
【问题描述】:
我无法想象这很困难,但我在任何地方都找不到有关如何使用 Jasmine 为具有 @Input 绑定的组件编写简单单元测试的文档。
我有一个这样的基本组件:
import { Component, Input } from '@angular/core';
@Component({
selector: 'action-button',
templateUrl: './action-button.component.html',
styleUrls: ['./action-button.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ActionButtonComponent {
@Input('tableId') tableId!: string;
@Input('actions') actions!: any;
@Input('dataSource') dataSource!: any;
constructor() { }
}
这是模板,action-button.component.html:
<button mat-flat-button
id="{{ tableId }}-create-button"
*ngIf="!dataSource.selection.hasValue()"
color="primary"
class="green-gradient-button"
(click)="actions.create.action()">
<mat-icon>add</mat-icon>
<span>{{ actions.create.text || 'CREATE' }}</span>
</button>
<button mat-flat-button
*ngIf="dataSource.selection.selected.length === 1"
class="gray-button"
(click)="actions.edit.action(dataSource.selection.selected[0].id)">
<span>{{ actions.edit.text || 'EDIT' }}</span>
</button>
<button mat-flat-button
*ngIf="dataSource.selection.hasValue()"
class="gray-button margin-left-10px"
id="{{ tableId }}-delete-button"
(click)="actions.delete.action(dataSource.selection.selected)">
<span>{{ actions.delete.text || 'DELETE' }}</span>
</button>
我只是使用 Angular CLI 生成的样板规范文件。 我在 Angular 11 上。 我的测试失败,错误如下:
Chrome 90.0.4430.212 (Mac OS 10.15.7) ActionButtonComponent should have Actions FAILED
TypeError: Cannot read property 'selection' of undefined
at ActionButtonComponent_Template (ng:///ActionButtonComponent.js:83:50)
我已经编写了数百个其他组件和服务的测试,所以我无法想象这有多难。只是无法在 SO 上找到我需要在这里做什么,只是为了模拟组件绑定。
【问题讨论】:
-
你能发帖
action-button.component.html吗? -
上面刚刚加的。
-
你还没有初始化dataSource
-
dataSource在绑定到此组件之前在父级中初始化。
标签: angular unit-testing data-binding jasmine