Verifying order of React elements with React Testing Library

Share on:

Recently I was working on sorting rows in a table in React and I wanted to be able to verify the rows sorted into the correct order. The table shows flaky tests (that is, tests that intermittently fail) and is built with Material Table. Material Table conveniently supports sorting out of the box by clicking on the column name.

Flaky tests table sort

For this app, I'm using React Testing Library for the component tests. Each cell for the latest-failure column has a data-testid attribute to find the individual cell and verify its contents, click on it, etc.

2  data-testid={`flaky-test-case-latest-failure-${rowData.idx}`}
4  {moment(rowData.latestCreatedTimestamp).format(
5    "MMM Do YYYY, h:mm a"
6  )}

But is there a way to grab all the cells and verify their order? There is - getAllByTestId to the rescue!

With getAllByTestId, we can pass exact: false as a config param to do a fuzzy-match and find all the elements where the data-testid attribute values match a specific substring:

1const latestFailureAscending = getAllByTestId(
2  "flaky-test-case-latest-failure",
3  {
4    exact: false,
5  }

Now we have a list of all the flaky-test-case-latest-failure elements - in order - so we can check each specific element matches the sorted values we expect:

2expect(latestFailureAscending[0]).toHaveTextContent("Oct 1st 2020");
3expect(latestFailureAscending[1]).toHaveTextContent("Oct 2nd 2020");
4expect(latestFailureAscending[2]).toHaveTextContent("Oct 3rd 2020");

Finally, bringing it all together for the full test case code:

 1it("should sort by latest failure", () => {
 2    const flakyTests = {
 3      tests: [
 4        createFlakyTest("2020-09-02", "2020-10-02"),
 5        createFlakyTest("2020-09-03", "2020-10-03"),
 6        createFlakyTest("2020-09-01", "2020-10-01"),
 7      ],
 8    } as RepositoryFlakyTests;
10    const { getByText, getAllByTestId } = render(
11      <RepositoryFlakyTestsTable flakyTests={flakyTests} />
12    );
14    getByText("Latest failure").click(); // Initial sort is ascending
16    const latestFailureAscending = getAllByTestId(
17      "flaky-test-case-latest-failure",
18      {
19        exact: false,
20      }
21    );
22    expect(latestFailureAscending.length).toBe(3);
23    expect(latestFailureAscending[0]).toHaveTextContent("Oct 1st 2020");
24    expect(latestFailureAscending[1]).toHaveTextContent("Oct 2nd 2020");
25    expect(latestFailureAscending[2]).toHaveTextContent("Oct 3rd 2020");

React Testing Library has many powerful queries available to verify components, including fuzzy-matching capabilities to easily verify lists of attributes and their order.