SPOTHUB / PLAYWRIGHT LEARNING LIBRARY

Playwright locators: choose the right element in a real test

A locator describes which element a test should use. In our checkout exercise, selecting the right quantity field matters before checking whether the total is correct.

Free learning resource · Official references below
01

Choose by meaning

Use getByLabel for the Quantity input and getByRole with the accessible name for Place demo order. A test ID is an explicit agreement with the application: our total uses data-testid=total. These choices make the intention visible when a teammate reads the test.

02

Diagnose multiple matches

An action that needs one element can fail if its locator matches several. Inspect the matches and narrow the search to the intended container. Selecting the first match can hide ambiguity and make the test depend on layout order.

03

Check whether a locator tests the requirement

In this exercise, the quantity field and total are separate controls. If the requirement concerns a button's user-facing name, a test ID alone would not verify that name. Role-based selection also does not replace a full accessibility audit.

04

Interview question: why avoid a long CSS selector?

A useful answer connects selector choice to maintenance. A chain tied to nested layout containers can break when presentation changes. Explain the control's meaning, how you confirmed uniqueness and when an explicit test ID is appropriate. Include a real failure you investigated once you have one.

Read the checkout example

This is the same test file provided by the linked lab. Follow the lab for installation, configuration and expected results.

import { test, expect } from '@playwright/test';

test('quantity changes the total', async ({ page }) => {
  await page.goto('/labs/checkout.html');
  await page.getByLabel('Quantity', { exact: true }).fill('2');
  await expect(page.getByTestId('total')).toHaveText('INR 200');
});
test('missing customer prevents confirmation', async ({ page }) => {
  await page.goto('/labs/checkout.html');
  await page.getByRole('button', { name: 'Place demo order' }).click();
  await expect(page.getByRole('alert')).toHaveText('Enter a demo customer name.');
  await expect(page.getByRole('status')).toBeEmpty();
});
Run this example in the practical lab →

Official references

Use these sources for current API behaviour and setup requirements. SPOTHUB is an independent training provider.

Continue learning

Find My IT Career Path