Enhancing Table Interactions in Playwright Using locator.filter
Automating interactions within tables that contain repeated elements, such as buttons with identical labels, can be challenging. Identifying the correct instance to interact with requires precise targeting to avoid unintended actions. Playwright’s locator.filter method provides a robust solution by allowing testers to narrow down locators based on specific criteria, such as text content within cells. This approach ensures that interactions occur with the intended elements, enhancing the reliability of automated tests.
Solution:
To interact with a specific button within a table row that contains certain text:
- Locate the table by its ID: Use getByRole('table') to select the table element.
- Identify all rows: Within the table, use getByRole('row') to select all rows.
- Filter rows: Apply filter with hasText to narrow down to the row containing the desired text.
- Find the button: Within the filtered row, use getByRole('button') to locate the target button.
- Click the button: Perform the click action on the identified button.
Example:
Consider the following HTML structure:
1<table id="product-table">
2<tr>
3<td>Item A</td>
4<td><button>View</button></td>
5</tr>
6<tr>
7<td>Item B</td>
8<td><button>View</button></td>
9</tr>
10</table>
To click the “View” button in the row containing “Item B”:
// Locate the table by its ID
const table = page.locator('#product-table');
// Locate all rows within the table
const rows = table.getByRole('row');
// Filter the rows to find the one containing 'Item B'
const targetRow = rows.filter({ hasText: 'Item B' });
// Within the filtered row, locate the 'View' button
const viewButton = targetRow.getByRole('button', { name: 'View' });
// Click the 'View' button
await viewButton.click();
Summary:
By combining locator.filter with role-based locators, testers can precisely target elements within complex structures like tables, even when multiple elements share the same labels. This method enhances the accuracy and reliability of automated interactions, ensuring that actions are performed on the correct elements. For more detailed information on locators, refer to Playwright’s official documentation.