Angular 测试点击事件

标签 angular typescript

目前我正在尝试了解有关 Angular (v2+) 中测试的更多信息,但我一直停留在 *ngFor 循环中测试点击事件。

这是 HTML 代码:

<div *ngIf="selectedHero">...</div>
<ul class="heroes">
  <li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

这是 onSelect 事件:

onSelect(hero:Hero):void{
    this.selectedHero = hero;
}

我有两个问题:

  1. 如何编写检查点击事件是否有效的测试?
  2. 如何编写一个测试,使 div 元素在设置了变量 selectedHero 时可见?

提前致谢!

更新 我编写了以下测试来检查点击事件:

it('should trigger a click event', () => {
  fixture.detectChanges();
  fixture.whenStable().then(() => {
    let comp = fixture.componentInstance;
    spyOn(comp, 'onSelect');

    let el = fixture.debugElement.query(By.css('li')).nativeElement.click();
    expect(comp.onSelect).toHaveBeenCalled();
  });
});

最佳答案

首先关注this guide在 Angular 测试上了解什么是 compfixtureel 变量。

How to write a test that checks if the click event works?

您需要监视 onSelect 方法并确保它已被触发:

it('should test click', () => {
    spyOn(comp, 'onSelect');
    el = fixture.debugElement.query(By.css('li')).nativeElement.click();
    expect(comp.onSelect).toHaveBeenCalled();
});

How to write a test that makes the div element visible when the variable selectedHero is set?

您需要测试该类是否应用于元素:

it('should test selected', () => {
    el = fixture.debugElement.query(By.css('li')).nativeElement;
    expect(el.classList.has('selected')).toBe(false);

    comp.onSelect(heroes[0]);
    expect(el.classList.has('selected')).toBe(true);
});

关于Angular 测试点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45544167/

相关文章:

javascript - TypeScript - 元素隐式具有 'any' 类型,因为类型 'string' 的表达式不能用于索引类型

javascript - Turn.js 类似于 ionic 2 的翻页书

javascript - typescript 错误 : Duplicate identifier 'LibraryManagedAttributes'

angular - 有没有人为 IdentityServer 3/4 创建任何 Angular2 身份验证包装类?

javascript - 访问自定义组件数据/方法

angular - Angular2 中的解析器和格式化器

angular - 如何对 AG-Grid 中标题名称为空的列进行排序

Typescript - 如何创建具有多种类型的数组

javascript - Angular2 中的全局对象

javascript - 未应用 bootstrap v4 上的 'btn-outline-*' 类