Rayrun

What are some best practices for selecting UI elements like buttons and text fields when writing tests using Playwright?

Answer

Best Practices for Selecting UI Elements in Playwright

When selecting UI elements like buttons and text fields in @playwright/test, follow these best practices:

  1. Use chaining and filtering: Narrow down your search by chaining locators together. This helps you find specific elements more easily.
import { test, expect } from '@playwright/test';

test('Find a button with a specific label', async ({ page }) => {
  await page.goto('https://ray.run/');
  const button = await page.locator('button').withText('Submit');
  await button.click();
  // Continue with your test
});
  1. Prefer user-facing attributes: Choose locators based on role, text, or test ID attributes instead of XPath or CSS selectors. This makes your tests more resilient to DOM structure changes.
import { test, expect } from '@playwright/test';

test('Find a text field using role attribute', async ({ page }) => {
  await page.goto('https://ray.run/');
  const textField = await page.locator('[role="textbox"]');
  await textField.fill('Sample text');
  // Continue with your test
});
  1. Consider using Playwright's test generator: This tool generates tests and locators based on your page's content, prioritizing role, text, and test ID locators.

For complex UI components like dropdown menus, creating helper functions can simplify testing and reduce code duplication. However, for basic UI elements, helper elements may not always be necessary or beneficial.

Remember to follow these best practices to ensure your tests remain accurate even if your DOM structure changes.

Thank you!
Was this helpful?
Still have questions?

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

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