Gustavo Sanchez
Gustavo Sanchez

Reputation: 11

AgGrid method onGridReady not being called on tests with React and Jest

I have an AGGrid with ServerSide.

And when I try to do the unit test in Jest/Enzyme or React Testing Library, it doesnt render the data. Just renders the Headers Columns. And while the grid renders properly in the application (with data displaying correctly on screen), when running unit tests in Jest/Enzyme or React Testing Library, only the column headers are rendered—no data. So I think the problem is related to the OnGridReady method that has the SSRM AGGrid.

This is the Test

import React from 'react';
import configureStore from 'redux-mock-store';
import TestAGGrid from '../Grid/TestAGGrid';
import { Provider } from 'react-redux';
import { mount, shallow as shallowRender, act } from 'enzyme';
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-enterprise';
import { render, screen } from '@testing-library/react';

describe('TESTAGGRRID', () => {
  let initialState;
  const mockStore = configureStore();
  const store = mockStore(initialState);

  const props = {
    isJest: true,
  };

  let agGridReact;

  it('should have a valid API after grid is ready', () => {
    let wrapper = mount(
      <Provider store={store}>
        <TestAGGrid {...props} />
      </Provider>,
    );

    agGridReact = wrapper.find(AgGridReact).instance();
    expect(agGridReact.api).toBeTruthy(); // Verifica la API

    //const rowCount = agGridReact.api.getDisplayedRowCount();
    //expect(rowCount).toBe(1);
  });

  it('contains expected rendered text in grid', async () => {
    render(<TestAGGrid />);

    //Test Headers Labels
    expect(screen.getByText('Athlete')).toBeTruthy();
    expect(screen.getByText('Country')).toBeTruthy();
    expect(screen.getByText('Year')).toBeTruthy();
    expect(screen.getByText('Sport')).toBeTruthy();
    expect(screen.getByText('Gold')).toBeTruthy();
    expect(screen.getByText('Silver')).toBeTruthy();
    expect(screen.getByText('Bronze')).toBeTruthy();

    //Test First Row
    //expect(screen.getByText('Michael Phelps')).toBeTruthy();
  });

  it('capturing snapshot of grid', () => {
    let rtlWrapper = render(<TestAGGrid />);
    const { container } = rtlWrapper;
    expect(container).toMatchSnapshot();
  });
});

And this is the component to test

import React, { useCallback, useMemo, useState } from 'react';
import { AgGridReact } from 'ag-grid-react';
import {
  ColDef,
  GridOptions,
  GridReadyEvent,
  IServerSideDatasource,
  IServerSideGetRowsRequest,
} from 'ag-grid-community';

export interface IOlympicData {
  athlete: string;
  age: number;
  country: string;
  year: number;
  date: string;
  sport: string;
  gold: number;
  silver: number;
  bronze: number;
  total: number;
}

const createServerSideDatasource: (server: any) => IServerSideDatasource = (
  server: any,
) => {
  return {
    getRows: (params) => {
      console.log('[Datasource] - rows requested by grid: ', params.request);
      // get data for request from our fake server
      const response = server.getData(params.request);
      // simulating real server call with a 500ms delay
      setTimeout(() => {
        if (response.success) {
          // supply rows for requested block to grid
          params.success({ rowData: response.rows });
        } else {
          params.fail();
        }
      }, 500);
    },
  };
};

function createFakeServer(allData: any[]) {
  return {
    getData: (request: IServerSideGetRowsRequest) => {
      // in this simplified fake server all rows are contained in an array
      const requestedRows = allData.slice(request.startRow, request.endRow);
      return {
        success: true,
        rows: requestedRows,
      };
    },
  };
}

const common: GridOptions = {
  domLayout: 'autoHeight',
  suppressMovableColumns: true,
  maxConcurrentDatasourceRequests: -1,
  defaultColDef: {
    resizable: true,
    sortable: true,
    floatingFilter: true,
    filterParams: {
      closeOnApply: true,
      suppressAndOrCondition: true,
    },
  },
};

const TestAGGrid = () => {
  const [columnDefs, setColumnDefs] = useState<ColDef[]>([
    { headerName: 'Athlete', field: 'athlete', cellClass: 'mono', width: 300 },
    { field: 'country', minWidth: 200 },
    { field: 'year' },
    { field: 'sport', minWidth: 200 },
    { field: 'gold' },
    { field: 'silver' },
    { field: 'bronze' },
  ]);
  const defaultColDef = useMemo<ColDef>(() => {
    return {
      flex: 1,
      minWidth: 100,
      sortable: false,
    };
  }, []);

  const onGridReady = useCallback((params: GridReadyEvent) => {
    fetch('https://www.ag-grid.com/example-assets/olympic-winners.json')
      .then((resp) => resp.json())
      .then((data: IOlympicData[]) => {
        // setup the fake server with entire dataset
        const fakeServer = createFakeServer(data);
        // create datasource with a reference to the fake server
        const datasource = createServerSideDatasource(fakeServer);
        // register the datasource with the grid
        params.api!.setGridOption('serverSideDatasource', datasource);
      });
  }, []);

  return (
    <div className="ag-theme-quartz">
      <AgGridReact<IOlympicData>
        columnDefs={columnDefs}
        defaultColDef={defaultColDef}
        gridOptions={common}
        rowModelType={'serverSide'}
        onGridReady={onGridReady}
      />
    </div>
  );
};

export default TestAGGrid;

Any help?

Tag: Problem when running the unit tests for AGGrid SSRM, no data rendered

Upvotes: 0

Views: 63

Answers (0)

Related Questions