微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

单元测试-onGridReady-Angular中的Ag-grid事件

如何解决单元测试-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 ,我认为你可能最终会陷入无限循环。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。