How to verify sorting of multiple ag-grid columns

2019-09-21 08:35发布

问题:

I am using protractor for e2e testing. There is a ag-grid table where multiple columns are sorted in ascending order.

How do i go about verifying this?
Picture of Sample table

回答1:

In AgGrid the rows might not always be displayed in the same order as you insert them from your data-model. But they always get assigned the attribute "row-index" correctly, so you can query for it to identify which rows are displayed at which index.

So in your E2E-tests, you should create two so-called "page objects" (a selector fo something in your view, separated from the text-execution code, google for page object pattern) like this:

// list page object
export class AgGridList {
  constructor(private el: ElementFinder) {}

  async getAllDisplayedRows(): Promise<AgGridRow[]> {
    const rows = $('div.ag-body-container').$$('div.ag-row');
    await browser.wait(EC.presenceOf(rows.get(0)), 5000);
    const result = await rows.reduce((acc: AgGridRow[], elem) => [...acc, new AgGridArtikelRow(elem)], []);
    return await this.sortedRows(result);
  }

  private async sortedRows(rows: AgGridRow[]): Promise<AgGridRow[]> {
    const rowsWithRowsId = [];
    for (const row of rows) {
      const rowIndex = await row.getRowIndex();
      rowsWithRowsId.push({rowIndex, row});
    }
    rowsWithRowsId.sort((e1, e2) => e1.rowIndex - e2.rowIndex);
    return rowsWithRowsId.map(elem => elem.row);
  }
}

// row page object
export class AgGridRow {
  constructor(private el: ElementFinder) {}

  async getRowIndex(): Promise<number> {
    const rowIndexAsString: string = await this.el.getAttribute('row-index');
    return parseInt(rowIndexAsString, 10);
  }
}

And in your test:

it('should display rows in right order', async () => {
  const rows = await gridList.getCurrentDisplayedRows(); // gridList is your AgGridList page object, initialised in beforeEach()
  // now you can compare the displayed order to the order inside your data model
});

What this code does: you make page objects for accessing the table as a whole and for accessing elements within a row. To accessing the list in the same order as it is displayed in the view, you have to get all displayed rows (with lazy loading or pagination it should be below 100, otherwise your implementation is bad), get the rowIndex from each of them, sort by it and only then return the grid-list to the test-execution (.spec) file.