带有 ChangeDetectionStrategy.OnPush 的 Angular 单元测试不起作用

use*_*366 5 unit-testing angular

我有这个简单的组件。

@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'app-spinner',
  template: `
    <ng-container *ngIf="loading; else valueTpl">
      <strong>loading....</strong>
    </ng-container>
    <ng-template #valueTpl>
      <span>{{ value }}</span>
    </ng-template>
  `
})
export class SpinnerComponent {
  @Input() loading = false;
  @Input() value!: string;
}
Run Code Online (Sandbox Code Playgroud)

在运行中它运行良好,但是当我去测试时测试失败

it('should show spinner when loading true', () => {
    component.loading = true;
    fixture.detectChanges();
    const strong = debugElement.query(By.css('strong'));
    const el: HTMLElement = strong.nativeElement;
    expect(el).not.toBeNull();
  });
Run Code Online (Sandbox Code Playgroud)

使用 ChangeDetectionStrategy.OnPush 测试组件的正确方法是什么?

更新

等待更好的解决方案,我解决了它:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [SpinnerComponent]
    })
      .overrideComponent(SpinnerComponent, {
        set: { changeDetection: ChangeDetectionStrategy.Default }
      })
      .compileComponents();
  }));
Run Code Online (Sandbox Code Playgroud)

小智 9

有效的方法是将组件的ChangeDetection 覆盖为默认值 ,并将ComponentFixtureAutoDetect 提供为 true

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [SpinnerComponent],
    providers: [
      {provide: ComponentFixtureAutoDetect, useValue: true}
    ]
  })
  .overrideComponent(SpinnerComponent, {
    set: { changeDetection: ChangeDetectionStrategy.Default }
  })
  .compileComponents();

  fixture = TestBed.createComponent(SpinnerComponent);
  component = fixture.componentInstance;
}));
Run Code Online (Sandbox Code Playgroud)

现在fixture.detectChanges()应该可以进行测试了。