CSS类的Angular HostBinding测试

时间:2019-03-12 10:30:41

标签: angular unit-testing

我有一个包装,里面装有货物,错误显示和实际内容。根据某些输入,我想显示一个或另一个。

我想测试是否有任何错误添加了'centered__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类被应用?

1 个答案:

答案 0 :(得分:0)

fixture.nativeElement.classList.contains('centered__holder')应该是您要寻找的。夹具还有其他绑定属性。