目前我正在尝试了解有关 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;
}
我有两个问题:
- 如何编写检查点击事件是否有效的测试?
- 如何编写一个测试,使 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 测试上了解什么是 comp
、fixture
和 el
变量。
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/