首页 > 解决方案 > 单元测试 - 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()被调用等,任何人都可以给出你的看法。

标签: angularkarma-jasmineangular-testkarma-coverageangular-unit-test

解决方案


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,你可能会陷入死循环。


推荐阅读