Search code examples
angulartypescriptjestjsag-grid-angularangular-observable

Unit Testing Ag Grid's column header with Jest and Angular Cli. Unable to find all columns from columnDefs


I'm using Jest and Angular Cli testing to verify column headers.

Trying to mimic this: https://www.ag-grid.com/javascript-grid-testing-angular/#testing-grid-contents

The issue is, i'm able to only find 2/5 columns from querySelectorAll('className');

I tried various approaches like naming them all with different header class and selecting by them, but i always got just 2/5 column headers.

I imagine it is something to do with rendering, but i might be wrong.

Here is all of the relevant files.

Test.spec.ts


import { ComponentFixture, async, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { AgGridModule } from 'ag-grid-angular';
import { TestGridComponent } from './test-grid.component';


describe('TestGridComponent', () => {
    let component: TestGridComponent ;
    let fixture: ComponentFixture<TestGridComponent >;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [
                AgGridModule.withComponents([TestGridComponent])
            ],
            declarations: [TestGridComponent],
            schemas: [NO_ERRORS_SCHEMA]
        }).compileComponents();

        fixture = TestBed.createComponent(TestGridComponent);
        component = fixture.componentInstance;

        fixture.detectChanges();
    }));

    // Works
    it('grid API is not available until  `detectChanges`', () => {
        expect(component.gridOptions.api).not.toBeTruthy();
    });

    // Fails with expect(received).toBeTruthy()  Received: undefined
    it('grid API is available after `detectChanges`', () => {
        fixture.detectChanges();
        expect(component.gridOptions.api).toBeTruthy();
    });


    // Able to get 'ID 'and 'Quantity' but not the rest of the header fields. I see them on the grid but not in the received.
    //
      output: expect(received).toEqual(expected) // deep equality

   // - Expected
   // + Received

    /*  Array [
    -   "ID",
    -   "Quantity",
    -   "someStuff1",
    -   "someStuff2",
    -   "someStuff3",
    +   "ID",
    +   "Quantity",
      ]
    */

    it('should display grid headers as expected', () => {        
        const elm = fixture.nativeElement;
        fixture.detectChanges();

        const grid = elm.querySelector('ag-grid-angular');
        // have also tried other classes as defined in my config.ts
    headerClass: 'testColumn' and searched querySelectorAll with that - same result.
        const headerCells = grid.querySelectorAll('.ag-header-cell-text');

        const headerTitles = Array.from(headerCells).map((cell: any) =>
            cell.textContent.trim()
        );        

        expect(headerTitles).toEqual(['ID', 'Quantity', 'someStuff1', 'someStuff2', 'someStuff3']);
    });   

});

test-grid.config.ts

export const defaultColDef = {
  filter: true,
  sortable: true,
  resizable: true,
  headerClass: 'testColumn'
};

export const columnDefs = [  
  {
    headerName: 'ID',
    headerTooltip: 'ID',
    field: 'id',
    cellStyle: colorSide,
    headerClass: 'header1'
  },  
  {
    headerName: 'Quantity',
    headerTooltip: 'Quantity',
    field: 'quantity',
    cellStyle: {'text-align': 'right'},    
    headerClass: 'header2'
  },  
  {
    headerName: 'SomeField1',
    field: 'SomeField1',
    headerTooltip: 'somefield1',
    cellStyle: {'text-align': 'right'},
    headerClass: 'header3'
  },
  {
    headerName: 'SomeField2',
    headerTooltip: 'SomeField2',
    field: 'someField2',
    cellStyle: {'text-align': 'left'},
    headerClass: 'header4'
  },
  {
    headerName: 'SomeField3',
    headerTooltip: 'SomeField3',
    field: 'SomeField3',
    cellStyle: {'text-align': 'left'},
    headerClass: 'header5'
  }
];

TestComponent-grid.ts

@Component({
  selector: 'web-client-app-common-grid',
  templateUrl: './test-grid.component.html'
})
export class TestGridComponent {
  // Data is coming from another container component, which was populated with the help of ngRx store.
  @Input() rowData;

  columnDefs: any;  
  defaultColDef: any;
  gridApi;
  gridColumnApi;
  gridOptions: GridOptions;  
  tooltipShowDelay;
  headerHeight: 48

  constructor() {
    this.columnDefs = columnDefs;
    this.defaultColDef = defaultColDef;
    this.tooltipShowDelay = 0;
  }

  onGridReady(gridOptions) {
    this.gridOptions= gridOptions;
    this.gridApi = gridOptions.api;
    this.gridColumnApi = gridOptions.columnApi;    
    this.gridOptions = <GridOptions>{
      headerHeight:75,   
    }  
  }

.html


<h1> Grid Works </h1>

<ag-grid-angular
  class="ag-vertical-lines"
  [rowData]="rowData"
  [columnDefs]="columnDefs"
  [defaultColDef]="defaultColDef"
  (gridReady)="onGridReady($event)"
  (firstDataRendered)="onFirstDataRendered()"
  [tooltipShowDelay]="tooltipShowDelay"
  style=" height: 100%; width: 100%;"
></ag-grid-angular>

jest.config.ts

module.exports = {
  name: 'test-web-client',
  preset: '../../jest.config.js',
  coverageDirectory: '../../target/coverage',
  reporters: [
    'default',
    ['jest-junit', { outputDirectory: './target/coverage' }]
  ],
  snapshotSerializers: [
    'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js',
    'jest-preset-angular/build/AngularSnapshotSerializer.js',
    'jest-preset-angular/build/HTMLCommentSerializer.js'
  ],
  testEnvironment: 'jest-environment-jsdom-fourteen'
};
module.exports.globals = {
  'ts-jest': {
    tsConfig: 'tsconfig.spec.json',
    stringifyContentPathRegex: '\\.html$',
    astTransformers: [require.resolve('jest-preset-angular/build/StripStylesTransformer')]
  }
};
module.exports.setupFilesAfterEnv = ['<rootDir>/src/test-setup.ts'];

I'm not sure where i'm going wrong, upon inspecting i see the selectors classes.

let me know if you need anymore info.

Please and Thanks.


Solution

  • Try to set suppressColumnVirtualisation to true on ag-grid-angular:

    <ag-grid-angular
        ...
        [suppressColumnVirtualisation]="true"
        ...
    >
    </ag-grid-angular>
    

    It should work now.