skip to content

How do you assert the rows of an Angular Material results table with MatTableHarness, and what do its cell-text methods return?

level: seniorimportance: nice to knowfreq 18%

answer

  1. rows, header rows, footer rows
  2. a grid of strings by index
  3. a map keyed by column
  4. the mat-column- class names columns
  5. only what is rendered

basics

~10 s

MatTableHarness gives row and cell harnesses plus two shortcuts: getCellTextByIndex() returns a string grid of the data rows, and getCellTextByColumnName() returns, per column, the data, header and footer texts.

solid answer

~30 s

I load `MatTableHarness` from `@angular/material/table/testing`, then `getRows()` gives `MatRowHarness` instances for the data rows, with `getHeaderRows()` and `getFooterRows()` alongside. For whole-table assertions, `getCellTextByIndex()` returns `string[][]`, one array per data row, headers excluded, and `getCellTextByColumnName()` returns an object keyed by column name with `text`, `headerText` and `footerText` arrays. Column names come from the `mat-column-<name>` class each column definition adds to its cells. Since version 21, `getNoDataRow()` returns the no-data row's harness or `null`. The harness reads only what is rendered, so a paginated table gives me the current page.

code

ts · 20 lines
ts
import {MatInputHarness} from '@angular/material/input/testing';
import {MatTableHarness} from '@angular/material/table/testing';

it('lists lentil recipes, then the empty state', async () => {
  const table = await loader.getHarness(MatTableHarness);
  const search = await loader.getHarness(MatInputHarness.with({label: 'Search recipes'}));

  await search.setValue('lentil');
  const columns = await table.getCellTextByColumnName();
  expect(columns['title'].text).toEqual(['Lentil soup', 'Lentil curry']);
  expect(columns['cookTime'].headerText).toEqual(['Cook time']);

  const [first] = await table.getRows();
  const [rating] = await first.getCells({columnName: 'rating'});
  expect(await rating.getText()).toBe('4.8');

  await search.setValue('zzz');
  expect(await table.getRows()).toEqual([]);
  expect(await table.getNoDataRow()).not.toBeNull();
});

go deeper

for a junior

Recall getRows(), getCellTextByIndex() and getCellTextByColumnName() and the testing entry point they come from.

for a middle

Explain the shape each shortcut returns and why headers are absent from the index grid.

for a senior

Explain where column names come from, why a paginated table yields one page, and how to assert the no-data state.

for a principal

Judge when whole-grid assertions help and when they make tests fragile to unrelated column changes, and set a team convention.

## The scenario The recipe search shows a `mat-table` of results with the columns `title`, `cookTime` and `rating`, a header row, and a no-data row reading **No recipes match "lentil"** when the search is empty. Tests need to check the order of titles after a search, the header labels, and the empty state. ## The harness classes Everything comes from `@angular/material/table/testing`: | Class | Finds | Key methods | |---|---|---| | `MatTableHarness` | `.mat-mdc-table`, so both `<table mat-table>` and `<mat-table>` | `getRows`, `getHeaderRows`, `getFooterRows`, `getNoDataRow`, `getCellTextByIndex`, `getCellTextByColumnName` | | `MatRowHarness` | data rows, excluding the no-data row | `getCells`, `getCellTextByIndex`, `getCellTextByColumnName` | | `MatHeaderRowHarness`, `MatFooterRowHarness` | header and footer rows | the same three row methods | | `MatNoDataRowHarness` | the row rendered by the table's no-data row template | the same row methods | | `MatCellHarness` | data cells | `getText`, `getColumnName` | Header, footer and no-data cells have their own cell harness classes with the same two methods. ## The two shortcuts **`getCellTextByIndex()`** returns `string[][]`: one inner array per **data** row, each cell's trimmed text in column order. Header and footer rows are not included. It is the quickest way to assert a whole result grid: ```ts expect(await table.getCellTextByIndex()).toEqual([ ['Lentil soup', '35 min', '4.8'], ['Lentil curry', '40 min', '4.6'], ]); ``` **`getCellTextByColumnName()`** returns an object keyed by column name. Each value holds three arrays: - `text`, the data cells of that column, top to bottom; - `headerText`, the header cells of that column; - `footerText`, the footer cells, empty when the table has no footer row. That suits assertions about one column, such as checking that titles come back in the expected order, without caring how many other columns exist. ## Where column names come from A cell's column name is not read from the header text. Each column definition gives its cells a CSS class `mat-column-<name>`, built from the column's name with characters that are not letters, digits, `_` or `-` replaced by `-`. `MatCellHarness.getColumnName()` reads that class, and it throws `Could not determine column name of cell.` if the class is missing. So the keys in `getCellTextByColumnName()` are your column definition names, such as `cookTime`, not the visible header `Cook time`. ## Filtering rows and cells - Row filters offer only the standard `selector` and `ancestor` options, so pick a row by position or by a class you add to the row template. - Cell filters add `text` and `columnName`: `row.getCells({columnName: 'rating'})` returns that row's rating cell, and both accept a string for an exact match or a RegExp. - `row.getCellTextByColumnName()` returns a flat `{column: text}` object for one row, handy when checking a single recipe. ## Choosing between the shapes | Assertion | Best fit | |---|---| | The whole result grid in order | `getCellTextByIndex()` | | One column's values, such as titles | `getCellTextByColumnName()[name].text` | | Header labels | `getHeaderRows()` then `getCellTextByIndex()` on the row, or `headerText` per column | | One cell in one row | `getRows()` then `row.getCells({columnName})` | Whole-grid assertions are compact but fail when someone adds an unrelated column; column-scoped assertions survive that change. ## Checking the empty state Since version 21, **`getNoDataRow()`** returns a `MatNoDataRowHarness` when the table is showing its no-data row and `null` otherwise, so the empty state is asserted without querying the DOM. Because `getRows()` excludes the no-data row, an empty search gives `getRows()` an empty array and a non-null `getNoDataRow()`. ## What the table harness does not do 1. It reads **rendered** rows only. With a paginator attached, `getCellTextByIndex()` returns the current page, not the whole data set. 2. It does **not sort or page**. Material ships separate harnesses for those, `MatSortHarness` with `MatSortHeaderHarness`, and `MatPaginatorHarness`, each in its own testing entry point. 3. It does not know about your data source. Assert on what the user sees in the cells, and test filtering logic where it lives.

  • Why does getCellTextByColumnName() key the results by cookTime rather than by the header text Cook time?
    The cell harness reads the column name from the `mat-column-<name>` CSS class that the column definition adds to every cell, not from the header. The key is therefore the column definition's name, made CSS-friendly by replacing unsupported characters with `-`; the visible header label appears only in the `headerText` array.
  • The results table has a paginator. Why does getCellTextByIndex() return ten rows when the search found forty?
    The table harness reads the rows that are rendered, and a paginated table renders only the current page. To check the other pages, drive `MatPaginatorHarness` from its own testing entry point, for example `goToNextPage()`, then read the table again.

  • getCellTextByIndex() includes the header row as its first entry.
  • Column names in getCellTextByColumnName() are the visible header labels.
  • MatTableHarness returns every row in the data source, even on other pages.
  • getRows() returns the no-data row when the table is empty.
  • MatTableHarness has methods to sort a column or change the page.

Assumes Angular Material 22; MatTableHarness.getNoDataRow() and MatNoDataRowHarness arrived in 21.