In @playwright/test, you can use the getByRole
method to locate and interact with elements based on their ARIA role, ARIA attributes, and accessible name. This approach is more resilient to DOM changes compared to using CSS selectors.
Consider the following DOM structure:
<h3>Sign up</h3>
<label>
<input type="checkbox" /> Subscribe
</label>
<br/>
<button>Submit</button>
You can interact with each element by its implicit role using getByRole
:
import { test } from '@playwright/test';
test('Interact with elements by role', async ({ page }) => {
await page.goto('https://ray.run/');
await expect(page.getByRole('heading', { name: 'Sign up' })).toBeVisible();
await page.getByRole('checkbox', { name: 'Subscribe' }).check();
await page.getByRole('button', { name: /submit/i }).click();
});
This code snippet demonstrates how to:
Using getByRole
allows you to interact with elements without needing a container or specific CSS selectors. For more efficient test scripts, consider using locators that are resilient to DOM changes and generating locators with Playwright's test generator tool.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].