Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the value of ngClass in angular test?

This is my component.html file which contains the ngClass attribute in the second span element:

<span class="container">
  <button mat-icon-button [disabled]="disabled" (click)="onButtonClicked()">
    <mat-icon>{{icon}}</mat-icon>
    <span class="badge" [ngClass]="((themes$ | async)[(activeTheme$ | async)].accent)" color="accent" *ngIf="badgeCount > 0">{{parseBadgeCount()}}</span>
  </button>
</span>
like image 362
D15 Avatar asked Mar 07 '18 15:03

D15


People also ask

What does NgClass do in Angular?

AngularJS ng-class Directive The ng-class directive dynamically binds one or more CSS classes to an HTML element. The value of the ng-class directive can be a string, an object, or an array. If it is a string, it should contain one or more, space-separated class names.

Can you have NgClass and class?

You can use both class and ngClass as the first one gives you the opportunity to apply a class that you want to implement in all cases under any circumstances and the later to apply classes conditionally.


1 Answers

If you are writing tests in Jasmine, you can verify things multiple ways. Here are a few examples. The last two are specifically looking at the value of the [ngClass] attribute, whereas the first two are just checking to see if a certain class was applied.

it('should have the "correct-class" CSS class applied', () => {
    // Do whatever you need for your arrange/act portions of your test
    ...

    // Assert
    const badge = fixture.debugElement.query(By.css('.badge'));
    expect(badge.classes['correct-class']).toBeTruthy();
});

it('should have the "correct-class" CSS class applied', () => {
    // Do whatever you need for your arrange/act portions of your test
    ...

    // Assert
    const badge: HTMLElement = fixture.debugElement.query(By.css('.badge')).nativeElement;
    expect(badge.classList).toContain('correct-class');
});

it('should have [ngClass] resolve to "correct-class"', () => {
    // Do whatever you need for your arrange/act portions of your test
    ...

    // Assert
    const badge = fixture.debugElement.query(By.css('.badge'));
    expect(badge.attributes['ng-reflect-ng-class']).toBe('correct-class');
});

it('should have [ngClass] resolve to "correct-class"', () => {
    // Do whatever you need for your arrange/act portions of your test
    ...

    // Assert
    const badge: HTMLElement = fixture.debugElement.query(By.css('.badge')).nativeElement;
    expect(badge.attributes['ng-reflect-ng-class'].value).toBe('correct-class');
});
like image 62
Daniel W Strimpel Avatar answered Sep 28 '22 12:09

Daniel W Strimpel