css 类的 Angular HostBinding 测试

标签 angular unit-testing

我有一个带有加载、错误显示和实际内容的包装器。根据某些输入,我想显示一个或另一个。

我想测试是否有任何错误添加了 'center__holder' 类

组件:

@Component({
  selector: 'sd-ui-state-wrapper',
  templateUrl: './ui-state-wrapper.component.html',
  styleUrls: ['./ui-state-wrapper.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UIStateWrapperComponent implements OnChanges {
  @Input() isLoading: boolean;
  @Input() errors: string[] | undefined;
  @HostBinding('class.centered__holder') centeredCss: boolean = false;

  [...]

  ngOnChanges(): void {
    this.centeredCss = this.isLoading || this.errors !== undefined && this.errors.length > 0;
  }
}

考试:

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [UIStateWrapperComponent],
  })
    .compileComponents();
}));

beforeEach(() => {
  fixture = TestBed.createComponent(UIStateWrapperComponent);
  component = fixture.componentInstance;
  component.errors = errorMock;
  fixture.detectChanges();
}));

it('should add centered__holder class', async (done) => {
  component.ngOnChanges();
  fixture.whenStable()
    .then(() => {
      console.log(fixture.debugElement.classes.centered__holder);
      console.log(component.centeredCss);

      expect(fixture.debugElement.classes.centered__holder)
        .toBeTruthy();
      done();
    });
});

但是控制台显示:true,false
我也试过 fixture.whenRenderingDone()
如何等待 HostBinding 类被应用?

最佳答案

fixture.nativeElement.classList.contains('center__holder') 应该是你要找的。固定装置上还有更多其他绑定(bind)属性。

关于css 类的 Angular HostBinding 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55119296/

相关文章:

node.js - 如何测试 Connect/Express 中间件?

Angular 4 参数与 json stringify

angular - 类正在使用 Angular 功能,但没有装饰。请添加一个显式的 Angular 装饰器

javascript - 如何在 Jasmine 中强制执行默认超时间隔?

c# - 单元测试异步方法 : The remote hostanme could not be resolved

c# - 响应式扩展测试调度程序模拟时间流逝

unit-testing - 如何测试以确保函数被调用?

javascript - 如何将 formArray 添加到 formGroup 中?

html - 如何防止元素文本换行

javascript - 在 Angular 2 中使用外部 JS 库