Using Playwright to Test Sorting in Multi-Column Tables

Using Playwright to Test Sorting in Multi-Column Tables

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:

  • Set up a simple HTML table with driver names

<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>        

  • Create a Page Object Model to interact with the table

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
  }
}        

  • Write a test to check alphabetical sorting

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

要查看或添加评论,请登录

Emanuel Sanchez的更多文章

社区洞察

其他会员也浏览了