Rayrun

What are the different methods to create a parameterized locator in Playwright?

Answer

Creating Parameterized Locators in Playwright

Creating parameterized locators in Playwright is a breeze. You can use methods like getByRole, CSS selectors, XPath selectors, or test ids.

Using getByRole

The getByRole method lets you locate elements based on their role and accessible name. Here's how you can use it:

page.getByRole('button', { name: 'Sign in' })

This will locate a button element with the accessible name "Sign in".

Using CSS or XPath Selectors

You can also use CSS or XPath selectors with the locator method. Playwright automatically detects them if you omit the prefix (css= or xpath=). But remember, long CSS or XPath chains can lead to unstable tests when the DOM structure changes.

page.locator('.my-class')
page.locator('//div[@id="my-id"]')

Using Test Ids

Defining an explicit testing contract using test ids is another great option. This approach can lead to more resilient tests.

page.locator('[data-testid="my-test-id"]')

Playwright also supports locating elements within Shadow DOM by default. But, there may be exceptions where certain locators do not work within Shadow DOM.

Remember, the key is to come up with locators that closely resemble how users perceive the page. For more insights, check out Understanding the Difference Between Locators and Selectors in @playwright/test.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

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