我正在用 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.gridApi
而失败是 undefined
,因此无法为网格 this.gridApi.setRowData(this.rowData)
分配值.
最佳答案
在编写涉及 ag-grid api 可用性的单元测试时,在这种情况下有两件事可以帮助您:
您可以尝试使用 this.gridOptions.api
(this.gridOptions.api.setRowData ...),而不是等待 gridReady
事件,因为大多数情况通常,它会更快初始化(在 onGridReady 触发之前)
您可以结合使用settimeout来做到这一点函数也是如此,当我过去遇到与您类似的问题时,我多次使用了该函数:
而不是:
this.gridApi.setRowData(this.rowData);
尝试:
setTimeout(() => { this.gridApi.setRowData(this.rowData);}, 100);
您可以增加 settimeout 的时间到 200、300、500 或更多,对我来说,大多数时候只需使用非常小的数字(10 毫秒)的 settimeout
即可。
settimeout这不是一个理想的解决方案,但在许多情况下都有效。第一个选项应该更干净,您甚至可以添加超时以使其正常工作。
使用 fakeAsync zone 而不是 async
也会有所帮助。
关于angular - ag-grid API 在 Angular 单元测试中未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65449177/