关于Angular Component changeDetection策略设置成OnPush的一个单元测试局限性

时间:2022-07-28
本文章向大家介绍关于Angular Component changeDetection策略设置成OnPush的一个单元测试局限性,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

局限性:如果Component的changeDetection的值为ChangeDetectionStrategy.OnPush而不是Default,那么fixture.detectChanges()只有在一个test spec里第一次调用才会生效。

这是Angular一个已知的bug:https://github.com/angular/angular/issues/12313

解决方案:

beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [OutletModule],
      declarations: [TableComponent],
      providers: [
        { provide: TableRendererService, useClass: MockTableRendererService },
      ],
    })
      .overrideComponent(TableComponent, {
        set: { changeDetection: ChangeDetectionStrategy.Default },
      })
      .compileComponents();

    fixture = TestBed.createComponent(TableComponent);
    tableComponent = fixture.componentInstance;
    tableRendererService = TestBed.inject(TableRendererService);
    fixture.detectChanges();
  });