目前,我正在尝试学习更多关于角测试(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;
}我有两个问题:
提前感谢!
更新我编写了以下测试来检查单击事件:
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();
});
});发布于 2017-08-07 10:04:17
首先,按照本指南进行角度测试,了解comp、fixture和el变量是什么。
如何编写检查单击事件是否有效的测试?
您需要监视onSelect方法并确保它被触发:
it('should test click', () => {
spyOn(comp, 'onSelect');
el = fixture.debugElement.query(By.css('li')).nativeElement.click();
expect(comp.onSelect).toHaveBeenCalled();
});在设置变量selectedHero时,如何编写使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);
});https://stackoverflow.com/questions/45544167
复制相似问题