9

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();
  });
});

1 Answer 1

15

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for pushing me to the right direction! I made a few changes to your code and it works like a charm now :)
great) you can then accept or upvote my answer if it helped)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.