【发布时间】:2021-04-03 13:06:51
【问题描述】:
我正在用 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 的测试工作,因为答案看起来有助于解决问题,我建议不要关闭问题,因为它有帮助为使用 ag-grid 库的组件编写单元测试。我已经在 github 中询问了一个关于此的具体问题,但链接已被删除,因此您可以根据我在为 ag-grid 编写单元测试时的经验来解决这个问题。
标签: angular unit-testing ag-grid ag-grid-angular