AgGrid Jest 单元测试 - 如何等待网格初始化

AgGrid Jest unit test - how to wait for the grid initialization

我正在为使用 AgGrid 的 Angular 组件编写开玩笑的单元测试。测试失败,因为使用 cellRenderer 的单元格未完成初始化。

我尝试添加一个 tick() 调用并使测试通过,但随后给出了关于 7 timer(s) still in the queue.

的错误

我也尝试了 await fixture.whenStable(); 但结果不一致,有时测试通过,有时在 expect 调用时失败,因为单元格未完成渲染。

在测试之前等待单元格渲染的正确方法是什么?

这是我使用 tick() 时的代码:

describe('MethodListComponent', () => {
  let component: MethodListComponent;
  let fixture: ComponentFixture<MethodListComponent>;

  beforeEach(fakeAsync(() => {
    TestBed.configureTestingModule({
      imports: [
        testingImports
      ],
      declarations: [MethodListComponent],
      providers: [
        { provide: MethodsService, useValue: mockMethodsService },
        { provide: AuthService, useValue: mockAuthService }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    });

    fixture = TestBed.createComponent(MethodListComponent);
    component = fixture.componentInstance;

    // make sure all columns are rendered for the tests
    component.activeMethodsGrid.gridOptions = {...component.activeMethodsGrid.gridOptions, 'suppressColumnVirtualisation': true};
  }));

  it('test archiving a test method', fakeAsync( async () => {
    // trigger onInit()
    fixture.detectChanges();

    tick(20);

    const archiveButtons = fixture.nativeElement.querySelectorAll(
      'ag-grid-angular .anticon-container'
    );
    expect(archiveButtons.length).toBe(2);
  }));
});

这是我使用await fixture.whenStable时的单元测试:

  it('test archiving a test method', async(done) => {
    // trigger onInit()
    fixture.detectChanges();
    
    await fixture.whenStable();
    
    const archiveButtons = fixture.nativeElement.querySelectorAll(
      'ag-grid-angular .anticon-container'
    );
    expect(archiveButtons.length).toBe(2);

    done();
  });

就其价值而言,事实证明 await fixture.whenStable 代码片段有效并且测试通过。它并不总是通过的原因是我正在对测试用例进行一些更改,而 运行 它们。