【问题标题】:How to write unit tests for Angular component with @Input bindings?如何使用 @Input 绑定为 Angular 组件编写单元测试?
【发布时间】: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


【解决方案1】:

您可以简单地在第一个 fixture.detectChanges() 之前分配您的 input 值,如 here 所示。注意他们是怎么做的comp.hero = ..,其中hero@Input()

要完全控制@Input() 的更改,您必须创建一个虚拟组件并将您的组件容纳在该虚拟组件内,并更改该虚拟组件的输入。查看使用主机组件(虚拟组件)here 进行的测试。

【讨论】:

    猜你喜欢
    • 2019-01-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-07
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    相关资源
    最近更新 更多