css 类的 Angular HostBinding 测试

sub*_*oca 6 unit-testing angular

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

我想测试是否出现任何错误,添加了“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;
  }
}
Run Code Online (Sandbox Code Playgroud)

考试:

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();
    });
});
Run Code Online (Sandbox Code Playgroud)

但控制台显示: true, false 我也尝试过fixture.whenRenderingDone()

如何等待 HostBinding 类被应用?

eva*_*jmg 4

Fixture.nativeElement.classList.contains('centered__holder') 应该是您正在寻找的。还有更多关于夹具以及其他绑定属性的信息。