角度测试点击事件



目前我正在尝试了解有关在 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();
});
});

首先,按照这个关于角度测试的指南来了解什么是compfixtureel变量。

如何编写一个测试来检查点击事件是否有效?

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

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

如何编写一个测试,使div 元素在 变量选定英雄已设置?

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

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

最新更新