Search code examples
angulartypescriptunit-testingag-gridag-grid-angular

ag-Grid: How can I access the gridApi from a Unit Test?


I am trying to unit test a function that includes calls to the gridApi, like this.gridApi.getSelectedRows();. When the unit test gets to this line, it gives this error: Failed: Cannot read property 'getSelectedRows' of undefined, because gridApi hasn't been defined yet.

How can I define the gridApi from a unit test? It is normally defined in the onGridReady function like this:

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;
    this.gridApi.sizeColumnsToFit();
  }

Is it possible to trigger onGridReady from a unit test? I don't know what params could be sent to it. Is there some other way to define this.gridApi instead?


Solution

  • this.gridApi and this.gridColumnApi are automatically initialzed in test cases. For that need to import AgGridModule from 'ag-grid-angular'. And Initialize component same as below code:

    let component: MyComponent;
    let fixture: ComponentFixture<MyComponent>;
    
    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [MyComponent],
            imports: [
                AgGridModule.withComponents([])
            ]
        }).compileComponents();
    
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    }));
    

    To test onGridReady Import on top of file.

    import { GridOptions } from "ag-grid-community";
    

    And declare a variable

    gridOptions: GridOptions = <GridOptions>{};
    

    write test case

    it('onGridReady called', () => {
    const data = {
        api: component.gridOptions.api,
        columnApi: component.gridOptions.columnApi
    }
    component.onGridReady(params);
    expect(component.gridApi).not.toBeNull();
    expect(component.gridColumnApi).not.toBeNull();
    });