首页 > 解决方案 > Angular 单元测试中未定义的 ag-grid API

问题描述

我正在为 Angular 编写 Ag-grid 的单元测试用例。

test.component.ts:

public gridApi: GridApi; 
public gridColumnApi;

constructor(private service: Service) {
 this.initializeAgGrid(); // this method just initializing the grid
}

ngOnInit(): void {
 this.setHraDashboardData();
}

onGridReady(params) {
 this.gridApi = params.api;
 this.gridColumnApi = params.columnApi;
 this.gridApi.sizeColumnsToFit();
}

setHraDashboardData() {
 this.service.getData(1).then((data) => {
   this.uiData = data;
   this.rowData = this.generateRowData(this.data); // this method writing some logic for UI
   this.gridApi.setRowData(this.rowData);
 });
}

test.component.spec.ts

beforeEach(() => {
  fixture = TestBed.createComponent(HraFormComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
});

it('grid API is available after `detectChanges`', async() => {
  await fixture.whenStable().then(()=>{
    fixture.detectChanges();
    const elm = fixture.debugElement.nativeElement;
    const grid = elm.querySelector('#Grid');
    const firstRowCells = grid.querySelectorAll('div[row-id="0"] div.ag-cell-value');
    const values = Array.from(firstRowCells).map((cell: any) => cell.textContent.trim());

    // assert
    expect(component.rowData[0].title).toEqual(values[0]);
  });
});

现在上面的测试用例由于 is 而失败component.gridApiundefined所以它不能为 grid 赋值this.gridApi.setRowData(this.rowData)

标签: angularunit-testingag-gridag-grid-angular

解决方案


在编写涉及 ag-grid api 可用性的单元测试时,在这种情况下,有两件事可以帮助您:

gridReady您可以尝试使用(this.gridOptions.api.setRowData ...)而不是等待事件,this.gridOptions.api因为大多数情况下,它会更快地初始化(在 onGridReady 触发之前)

您也可以结合使用settimeout函数来做到这一点,当我过去遇到与您类似的问题时,我多次使用它:

代替:

this.gridApi.setRowData(this.rowData);

尝试:

setTimeout(() => { this.gridApi.setRowData(this.rowData);}, 100);

您可以将settimeout的时间增加到 200、300、500 或更多,对我来说,大部分时间只使用settimeout非常小的数字(10 毫秒)就可以了。

settimeout不是一个理想的解决方案,但在许多情况下都有效。第一个选项应该更干净,您甚至可以添加超时以使其正常工作。

使用fakeAsync zone 而不是async一个也将有所帮助。


推荐阅读