Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular testing click event

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:

  1. How to write a test that checks if the click event works?
  2. 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();
  });
});
like image 480
Stefan Avatar asked Aug 07 '17 09:08

Stefan


1 Answers

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);
});
like image 83
Max Koretskyi Avatar answered Nov 01 '22 21:11

Max Koretskyi