What are some best practices for using locators in @playwright/test?


Best Practices for Using Locators in @playwright/test

When it comes to using locators in @playwright/test, there are a few best practices you should follow.

Use User-Facing Attributes

Firstly, prefer user-facing attributes over XPath or CSS selectors. The DOM can change, and relying on its structure can lead to failing tests. For instance, if a button's CSS class changes, your test might break.

// Instead of this
const button = page.locator('.submit-button');

// Do this
const button = page.locator('[role="button"]');

Chain and Filter Locators

Secondly, use chaining and filtering when selecting elements. You can chain locators to narrow down the search or filter locators by text or another locator.

// Chaining locators
const buttonInForm = page.locator('form').locator('[role="button"]');

// Filtering locators
const buttonWithText = page.locator('[role="button"]').withText('Submit');

Use Playwright's Codegen Feature

Playwright's codegen feature can generate tests and pick locators for you. It prioritizes role, text, and test id locators, making your tests more resilient.

// Run this command in your terminal
npx playwright codegen https://ray.run

Use New Selector Engines

Finally, Playwright provides several new selector engines, like the nth selector engine and the visible selector engine. These can be combined with other selector engines for more precise element selection.

// Using nth selector engine
const thirdListItem = page.locator('li:nth(3)');

// Using visible selector engine
const visibleDiv = page.locator('div:visible');

By following these practices, you can create robust automated testing scripts that can handle changes in web pages' structures over time.

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 Questions

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 luc@ray.run.