Unit testing - onGridReady - Ag-grid event in Angular

9.5k views Asked by At

I am having a function like below in my component file like below

onGridReady(params) {
  this.gridApi = params.api;
  this.columnApi = params.columnApi;
  this.gridApi.setDomLayout('autoHeight');
  this.gridApi.sizeColumnsToFit();
  params.api.setRowData(this.deviceConfigurations);
}

For the above function I am writing the spec like the below one

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();
    });
  });

The spec passes as well as the coverage is done for the above function. But I would like to know whether is it the correct way or writing the spec or do I need to write more specs like to sizeColumnsToFit() has been called etc., Could anyone can give your view about it.

1

There are 1 answers

0
rando22 On

onGridReady() should be called automatically after ngOnInit(), so my preference would be to test what onGridReady() is doing.

This is how I am doing it:

    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...
        });

    }));

My ts file looks something like this:

    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~ I think you might end up with an endless loop if you call setRowData in the onGridReady() method.