我正在以角度编写 Ag-grid 的单元测试用例。
测试.组件.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);
});
}
测试.组件.规格.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
is undefined
,所以它无法为网格分配值this.gridApi.setRowData(this.rowData)
.
在编写涉及 ag-grid api 可用性的单元测试时,在这种情况下,有两件事可以帮助您:
而不是等待gridReady
事件,您可以尝试使用this.gridOptions.api
(this.gridOptions.api.setRowData ...) 因为大多数时候,它初始化得更快(在 onGridReady 触发之前)
您可以结合使用来做到这一点设置超时函数也是如此,当我过去遇到与您类似的问题时,我多次使用了该函数:
代替:
this.gridApi.setRowData(this.rowData);
Try:
setTimeout(() => { this.gridApi.setRowData(this.rowData);}, 100);
您可以增加时间设置超时到 200、300、500 或更多,对我来说,大部分时间只是使用settimeout
用非常小的数字(10 毫秒)就可以了。
The 设置超时这不是一个理想的解决方案,但在许多情况下都有效。第一个选项应该更干净,您甚至可以添加超时以使其正常工作。
Use a 假异步区而不是async
一个也会有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)