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:
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();
});
});
First, follow this guide on Angular testing to learn what comp
, fixture
and el
variables are.
How to write a test that checks if the click event works?
You need to spy on onSelect
method and ensure it was triggered:
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?
You need to test that the class is applied to the element:
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With