如何在角度测试中检索ngClass的值?

时间:2018-03-07 15:31:19

标签: angular jasmine

这是我的component.html文件,其中包含第二个span元素中的ngClass属性:

<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>

1 个答案:

答案 0 :(得分:4)

如果您在Jasmine中编写测试,则可以通过多种方式验证事物。这里有一些例子。最后两个是专门查看[ngClass]属性的值,而前两个只是检查是否应用了某个类。

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