Chapter 38: Role, text, label and test-id locators
Automation learning lab
Playwright Automation
Self Study Guide
Start from zero. Learn JavaScript and TypeScript, automate browsers, and build reliable end-to-end tests.
Role, text, label and test-id locators
getByRole uses accessibility roles and accessible names, getByLabel finds form controls by labels, and getByText finds text. getByTestId uses an explicit test-id contract. Choose locators that express what a user sees or a stable agreed identifier.
How it works
Step-by-step walkthrough
- Create labeled controls
- Locate by label
- Assert a button is visible
Example
import { test, expect } from '@playwright/test';
test('chapter 38 practice', async ({ page }) => {
await page.setContent('<label>Email <input></label><button>Continue</button>');
await page.getByLabel('Email').fill('qa@example.com');
await expect(page.getByRole('button', { name: 'Continue' })).toBeVisible();
});Make locators unique instead of using first() to hide ambiguity.
Practice application screenshot
✎ Your practice task
Add data-testid="continue" and locate it by test id.
Knowledge check
Which locator targets a labeled input?
🌐 Continue learning
60-chapter learning path
Start at chapter 1, or choose any topic. Your progress is tracked separately for each chapter.
JavaScript fundamentals
TypeScript fundamentals
Playwright • setup & locators
Playwright • interactions & assertions
Playwright • framework & debugging
Playwright • real-world automation
Interactive practice lab
Try the controls below and observe the corresponding Playwright locator instructions. This browser demo does not execute Node.js or Playwright Test; copy the code to your local Playwright project to automate it.
Task manager demo
Suggested automation
Actions on the demo update these examples. In your local test use a page that contains the same controls.
Download a standalone lab page, then serve it locally (for example with Python's http.server). Navigate to it in a Playwright test.