angular - 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.gridApi
,undefined
所以它不能为 grid 赋值this.gridApi.setRowData(this.rowData)
。
解决方案
在编写涉及 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
一个也将有所帮助。
推荐阅读
- android - 在 Android 中从 Fragment 打开 Activity
- dart - 谁能给我一个想法,将会话超时重定向到颤振的登录屏幕?
- flutter - 尽管 SingleChildScrollView 出现 Flutter 溢出异常
- c# - C#检查字符串是否存在,如果存在则显示该字符串
- python - 对 Flask 后端响应正文的获取请求为 null 且没有 cors 并且在没有 no-cors 的情况下失败
- python - python中matplotlib中的绘图大小= 1/{N∗⌈log2N⌉∗[(1/70)/60]}?
- ios - 需要在Objective C中获取Grib File数据
- java - char 值如何传递给 int 参数的方法
- node.js - 更新 MongoDB 中的子子数组项
- amazon-web-services - 无需单击亚马逊 sumerian 上的开始按钮即可开始场景