Test Id Locator in Playwright
Test Id Locator in Playwright: definition, detailed explanation, practical usage, examples, mistakes, interview notes, and practice for Playwright automation.
Definition and Brief Explanation
Definition: A test id locator finds elements by a stable test-only attribute such as data-testid.
Explanation: Test ids are useful when user-facing text changes often, when controls have repeated labels, or when the UI has no reliable accessible name. A good test id is stable and describes business intent, not styling.
Why It Matters
- It makes tests easier to read because the locator describes the target element clearly.
- It reduces flaky failures caused by layout changes or generated CSS classes.
- It works with Playwright auto-waiting, so actions and assertions wait for the element state.
- It supports maintainable Page Object Model code because selectors are meaningful.
How It Works
- Identify the element by user-facing meaning first: role, label, text, placeholder, alt text, or title.
- Confirm the locator points to the intended element and is unique when used for an action.
- Use filters, chaining, or test ids when the page has repeated controls.
- Avoid positional locators unless order is the behavior being tested.
Syntax and Examples
Example 1: Test id locator
await page.getByTestId('submit-order').click();
Explanation: Uses a stable test hook when user-facing locators are not unique enough.
Example 2: Custom test id attribute
use: { testIdAttribute: 'data-qa' }
Explanation: Configures Playwright to use data-qa instead of data-testid.
Common Mistakes
- Using generated CSS classes as the first option.
- Using broad text that appears in many places.
- Adding nth() only to silence strict mode.
- Storing element handles instead of using locators.
Interview Notes
- What is a Test Id Locator in Playwright?
- When would you choose Test Id Locator?
- How do you make the locator unique?
- What makes this locator stable or unstable?
Practice Task
Create a small Playwright example for Test Id Locator. Add one positive assertion, one note about what can go wrong, and one improvement that would make the test more maintainable.