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

Click a column header to sort the table
AnnaKowalski28100User
GraceOkafor2791Admin
JohnSmith329Admin
LenaNovak387Manager
MichaelBrown4142Manager
OmarHaddad3623User
PiotrZając3064User
SarahWilson3510User
TomBecker2585User
YukiTanaka3358Manager