Sortable Table
Practice sorting table data.
Proving a table is sorted
Read the sort direction from aria-sort
The sorted column's header has aria-sort="ascending" or "descending"; the others have "none". Screen readers announce it, and it is the most reliable way to check the direction:
const ageHeader = page.getByRole('columnheader', { name: 'Age' });
await page.getByRole('button', { name: 'Age' }).click();
await expect(ageHeader).toHaveAttribute('aria-sort', 'ascending');Compare the column with a sorted copy
Read the whole column, sort a copy yourself, and compare the two. Asserting only the first row proves very little:
// Score is the 4th column (index 3).
const scoreCells = page.locator('tbody tr').locator('td:nth-child(4)');
await page.getByRole('button', { name: 'Score' }).click();
await expect(page.getByRole('columnheader', { name: 'Score' }))
.toHaveAttribute('aria-sort', 'ascending');
const scores = (await scoreCells.allTextContents()).map(Number);
expect(scores).toEqual([...scores].sort((a, b) => a - b));The number trap
allTextContents() returns strings. Sorted as text, "10" comes before "7". A test that forgets .map(Number) sorts its copy as text, compares the correct table with the wrong order, and fails. The Score column is designed to show exactly that.
Read the column only after the
aria-sort assertion has passed. That makes sure the table has re-rendered before you take the snapshot.Sortable Users
| Anna | Kowalski | 28 | 100 | User |
| Grace | Okafor | 27 | 91 | Admin |
| John | Smith | 32 | 9 | Admin |
| Lena | Novak | 38 | 7 | Manager |
| Michael | Brown | 41 | 42 | Manager |
| Omar | Haddad | 36 | 23 | User |
| Piotr | Zając | 30 | 64 | User |
| Sarah | Wilson | 35 | 10 | User |
| Tom | Becker | 25 | 85 | User |
| Yuki | Tanaka | 33 | 58 | Manager |