Using Playwright to Test Sorting in Multi-Column Tables
Emanuel Sanchez
Software Engineer | Test Automation, Linux, CI/CD, Cloud Computing, ML
Today I explored how to assert if names in a table column were sorted alphabetically using Playwright and Typescript. Here's a quick guide on implementing this test using Playwright:
<div class="ag-center-cols-container">
<div class="ag-row">
<div class="ag-cell" col-id="driverName">Lewis Hamilton</div>
<div class="ag-cell" col-id="team">Mercedes</div>
<div class="ag-cell" col-id="points">190</div>
</div>
<!-- More rows... -->
</div>
export class DriversPage {
public driversTable: Locator;
private baseURL: string;
constructor(private page: Page, baseURL: string = 'https://localhost:3000') {
this.driversTable = page.locator('.ag-center-cols-container *[col-id="driverName"]');
this.baseURL = baseURL;
}
async open() {
await this.page.goto(`${this.baseURL}/drivers`);
}
async getDriverNames(): Promise<string[]> {
const allNames = await this.driversTable.allInnerTexts();
return allNames.slice(1); // Remove header
}
}
test('should display F1 drivers in alphabetical order', async ({ page }) => {
const driversPage = new DriversPage(page, 'https://localhost:3000');
await page.goto('/drivers'); // Navigate to the drivers page
const driverNames = await driversPage.getDriverNames();
const sortedNames = [...driverNames].sort();
expect(driverNames).toEqual(sortedNames);
});
This test uses JavaScript's default sort() method, which works well for simple Latin-alphabet names. For more complex scenarios involving accents or different alphabets, consider using localeCompare().
Remember, effective testing is about balancing simplicity with robustness. This approach offers a straightforward way to verify alphabetical sorting in Playwright tests.
#Playwright #TypeScript #WebTesting #QA