1

I an trying to write the unit test using jasmine for ag-grid.

  1. HTMl

     <ag-grid-angular
     style="width: 500px; height: 400px;"
     class="ag-theme-alpine"
     [rowData]="rowData"
     [columnDefs]="columnDefs"
     rowSelection='single'
     (gridReady)="onGridReady($event)"
     >
     </ag-grid-angular>
    
  2. .ts

     import { Component, Input, OnInit } from '@angular/core';
     import { ColDef } from 'ag-grid-community';
     import { DataGrid } from 'src/app/shared/models/datagrid.model';
     @Component({
     selector: 'app-simple-view',
     templateUrl: './simple-view.component.html',
     styleUrls: ['./simple-view.component.scss']
     })
     export class SimpleViewComponent implements OnInit {
     @Input('data') data: any | undefined;
    
     columnDefs: ColDef[] = [
     { field: 'Geography', sortable: true },
     { field: 'Category', sortable: true },
     { field: 'DataType', sortable: true }
    ];
    
    rowData: DataGrid[] | undefined;
    
    public gridApi: any;
    
    constructor() { }
    
    ngOnInit(): void {
     this.rowData = this.data;
    }
    
    onGridReady(params: any) {
     this.gridApi = params.api;
    
    }
    }
    
  3. spec.ts

     it('grid API is available after `detectChanges`', () => {
     fixture.detectChanges();
     expect(component.gridOptions.api).toBeTruthy();
     });
    

this test method is failing with the below error

SimpleViewComponent > grid API is available after detectChanges Expected undefined to be truthy. Error: Expected undefined to be truthy. at at UserContext. (http://localhost:9876/karma_webpack/webpack:/src/app/features/overview/components/simple-view/simple-view.component.spec.ts:45:31) at Generator.next () at asyncGeneratorStep (http://localhost:9876/karma_webpack/webpack:/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js:3:1)

1 Answers1

1

For these kind of situations (Not knowing when AGGrid will resolve what it will resolve), I like to use a waitUntil utility function.

// Put this in a utils section of the project with the name of waitUntil.ts
// This function will keep retrying and wait until the function is truthy
// before proceeding

import { interval } from 'rxjs';
.....
export const waitUntil = async (untilTruthy: Function): Promise<boolean> => {
  while (!untilTruthy()) {
    await interval(25).pipe(take(1)).toPromise();
  }
  return Promise.resolve(true);
};
// Use waitUntil with async await

it('grid API is available after `detectChanges`', async () => {
   fixture.detectChanges();
   // wait until gridOptions.api is truthy
   await waitUntil(() => !!component.gridOptions.api);
   expect(component.gridOptions.api).toBeTruthy();
 });

I remember when I was using AgGrid with Angular unit tests, I had to use waitUntil a lot. If that test times out (the await does not resolve), then I am thinking there is something wrong with the setup of the test.

AliF50
  • 16,947
  • 1
  • 21
  • 37