ag-grid API 在 Angular 单元测试中未定义

ag-grid API Undefined in Angular unit testing

我正在 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]);
  });
});

现在由于 component.gridApiundefined,上面的测试用例失败了,所以它无法为网格 this.gridApi.setRowData(this.rowData).

赋值

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

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

您也可以结合使用 settimeout 函数来执行此操作,我在过去遇到与您类似的问题时多次使用该函数:

而不是:

this.gridApi.setRowData(this.rowData);

尝试:

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

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

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

使用 fakeAsync 区域而不是 async 区域也会有所帮助。