angular - 单元测试 - onGridReady - Angular 中的 Ag-grid 事件
问题描述
我的组件文件中有如下功能,如下所示
onGridReady(params) {
this.gridApi = params.api;
this.columnApi = params.columnApi;
this.gridApi.setDomLayout('autoHeight');
this.gridApi.sizeColumnsToFit();
params.api.setRowData(this.deviceConfigurations);
}
对于上述功能,我正在编写如下规范
describe('#onGridReady()', () => {
const params = {
api: new MockGridApi(),
ColumnApi: new MockColumnApi(),
};
it('call the function', () => {
spyOn(component, 'onGridReady').and.callThrough();
component.onGridReady(params);
expect(component.onGridReady).toHaveBeenCalled();
});
});
规范通过了,并且覆盖了上述功能。但我想知道它是否是正确的方法或编写规范,或者我是否需要编写更多的规范,比如sizeColumnsToFit()
被调用等,任何人都可以给出你的看法。
解决方案
onGridReady() 应该在 ngOnInit() 之后自动调用,所以我的偏好是测试 onGridReady() 正在做什么。
这就是我的做法:
import {waitForAsync} from '@angular/core/testing';
// 1) Add waitForAsync() to my test
it('should do things onGridReady() is supposed to do', waitForAsync(() => {
const expectedRowData = [{id: 1, dataPoint: 'someDataPoint'}];
// call ngOnInit directly
component.ngOnInit();
fixture.detectChanges();
// wait for the fixture to stabilize
fixture.whenStable().then(() => {
console.log(' ==> stable!');
expect(component.gridOptions.rowData).toEqual(expectedRowData);
// whatever other tests...
});
}));
我的 ts 文件看起来像这样:
onGridReady(params: any): void {
console.log('the grid is ready!');
this.gridApi = params.api;
this.columnApi = params.columnApi;
this.gridApi.setDomLayout('autoHeight');
this.gridApi.sizeColumnsToFit();
this.gridOptions.rowData = this.deviceConfigurations;
}
PS~ 我想如果你在 onGridReady() 方法中调用 setRowData,你可能会陷入死循环。
推荐阅读
- javascript - `leftJoin()` 不使用 Knex.js 返回带有 Objection ORM 的连接表数据
- python - 我可以通过在 python 中的查询将数据库表与 Excel 文件连接起来吗?
- python - PyCharm:运行脚本时激活 venv
- python - 如何设置记录器对象的记录级别?
- r - 将函数应用于数据框的某些列,同时将结果存储在原始数据框中
- jquery - Jquery TR 可排序,用于单独的手风琴
- c# - 如何使用 C# 网络服务?
- forms - 为什么“toFillForm”在 jest-puppeteer 中不起作用?
- kubernetes - Kubernetes 主节点未接收到内部 IP
- java - 如何在快速 android 网络库中的参数中发送数组