angular - 如何在 Angular Testing 中检索 ngClass 的值?

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

最佳答案

如果您在 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');
});

关于angular - 如何在 Angular Testing 中检索 ngClass 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49155660/

相关文章:

android - 我正在尝试发布到本地主机 API,我得到 --> java.net.ConnectException : Connection timed out

javascript - 使用 Jasmine 监视 AngularJS 服务中的私有(private)函数

javascript - 测试使用 setInterval 或 setTimeout 的 Angular2 组件

node.js - Node : How do I order my tests to run synchronously? 中的 Protractor

javascript - 对 Jasmine spy 的重置调用未返回

angular - ng-content angular 2 不适用于自举组件

angular - 如何将服务注入(inject) Angular 的scrollOffset函数

css - Angular Flex 布局总是显示滚动条

javascript - 如何在 Angular 中实现表单投影?

javascript - 使用 Protractor 按类名定位按钮