Tag: Angular

  • Querying Multiple Elements with CSS in Angular Tests

    When writing an Angular component, we often want to test our component changes it’s HTML template as expected.

    To detect changes made to a single element, we can use CSS to query the DOM. In the example below, we’re checking for a span element with an active class:

    // Trigger changes
    component.keyboardCharacters = ['A'];
    fixture.detectChanges();
    
    // Assert on changes
    const active = fixture.debugElement.query(By.css('span.active'));
    expect(active.nativeElement.textContent).toEqual(' A ');

    However, on some occasions, we may want to check that our CSS selector matches multiple elements:

    // Trigger changes
    component.keyboardCharacters = ['J', 'K'];
    fixture.detectChanges();
    
    // Assert on first matching element
    const active1 = fixture.debugElement.queryAll(By.css('span.active'))[0];
    expect(active1.nativeElement.textContent).toEqual(' J ');
    
    // Assert on second matching element
    const active2 = fixture.debugElement.queryAll(By.css('span.active'))[1];
    expect(active2.nativeElement.textContent).toEqual(' K ');

    In the example above, we use fixture.debugElement.queryAll, which returns an array of matching elements. We can then pick out the element we’re after specifying an array index.