At the moment I'm trying to learn more about testing in Angular (v2+), but I'm stuck at testing click events in a *ngFor loop.
This is the HTML-code:
<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>
This is the onSelect event:
onSelect(hero:Hero):void{
this.selectedHero = hero;
}
I have two questions:
- How to write a test that checks if the click event works?
- How to write a test that makes the div element visible when the variable selectedHero is set?
Thanks in advance!
Update I wrote the following test to check the click event:
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();
});
});