首页 > 解决方案 > AgGrid Jest 单元测试 - 如何等待网格初始化

问题描述

我正在为使用 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();
  });

标签: angularjestjsag-grid

解决方案


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


推荐阅读