问题描述
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 ,我认为你可能最终会陷入无限循环。