QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright

Locators

Locators, and Locator vs ElementHandle

A Locator is a search recipe, not a found node: Playwright searches again on every action, so a DOM re-render does not make it stale. An ElementHandle holds one concrete node and fails once that node is replaced, which is why the documentation recommends locators. Pick locators by user-facing traits: role with name, label, text, then test id, and CSS or XPath only as a last resort.

Playwright · Locators

A designer renamed a button class and 40 tests failed. How do you write locators that survive it?

A team has 40 tests that click .btn-primary. A style refactor renames the class and the whole suite goes red while the app works fine. Another test keeps a node from page.$, and after a re-render the click goes to a dead element. Both problems share one cause: the test describes the element by its markup rather than by what the user sees. This lesson answers three questions: which locator to pick first, why a Locator is lazy, and why it replaced ElementHandle.

What a Locator is and why it is lazy. A Locator does not hold a found element. It is a search recipe: a string such as getByRole('button', { name: 'Save' }) plus a reference to the page. The search runs every time an action or an assertion is called. That is deliberate, because modern pages redraw the DOM constantly and a framework can replace a node between two lines of a test. If a locator held a concrete node, every re-render would invalidate it (in Selenium that is StaleElementReferenceException). A recipe simply finds the new node on the next action and also waits for the element to be ready (attached, visible, stable, enabled; see the actionability lesson).

const save = page.getByRole('button', { name: 'Save' }); // nothing is searched
await page.goto('/profile');   // a locator can be created before the page opens
await save.click();            // search and waiting happen here
await page.reload();
await save.click();            // the same locator finds the new node

Locator priority. Playwright recommends user-facing attributes: what the user sees and hears, not how the page is built. A practical ladder is: role with an accessible name, then label, placeholder and text, then test id, and CSS or XPath last. The higher the rung, the less the test depends on markup and the more it checks accessibility: if a button cannot be found by role and name, a screen reader will not find it either.

The locator choice ladder

1 getByRolebuttons, links, fields with an accessible name 2 getByLabelform fields with a label 3 getByPlaceholderfield with only a placeholder 4 getByTexttext without a role: paragraph, message 5 getByAltText, getByTitleimages with alt, elements with title 6 getByTestIdno role or text, dynamic content 7 page.locator('css')last resort: depends on markup
Figure 1. The top is the most stable and closest to the user, the bottom is the most fragile. Take a lower rung only when the higher one does not fit.
LocatorTypical use
getByRoleButtons, links, headings, checkboxes and other ARIA roles
getByLabelForm fields with a label
getByTextNon-interactive text: paragraphs, messages
getByTestIdDynamic content, icons, multilingual UI

Example: before and after. A test that survives redesigns looks at meaning, not at markup:

// before: tied to classes and DOM position
await page.locator('div.cart > div:nth-child(2) button.btn-primary').click();
// after: role, name and context
await page
  .getByRole('region', { name: 'Cart' })
  .getByRole('button', { name: 'Place order' })
  .click();
await expect(page.getByText('Order created')).toBeVisible();

The second version survives a new class and a change of nesting. It fails only when something the user would notice changes: the button's name or its disappearance. That is the right kind of failure.

Strict mode. If a locator matches several elements and the action expects one (click, fill), Playwright throws instead of picking the first. This is a safeguard: the test will not click "some" button and pass by accident. The message looks like this (shortened):

Error: strict mode violation:
  getByRole('button', { name: 'Delete' }) resolved to 3 elements:
    1) <button class="btn">Delete</button> aka …
    2) <button class="btn">Delete</button> aka …

The right reaction is to find out why there are three and narrow the locator (the next lesson). Strict mode also applies to single-element assertions such as toBeVisible, while collection methods (count, all, toHaveCount, toHaveText with an array) do not apply it.

Locator versus ElementHandle. An ElementHandle holds a reference to one concrete DOM node captured once (page.$, locator.elementHandle()). It never re-resolves the element and has no strict mode: actions on it wait for actionability of that one node only and throw once it is replaced. The Playwright docs discourage it and recommend locators; page.$ and page.$$ belong to the same discouraged group.

A recipe or a node reference

Typical

ElementHandle

Holds one concrete node. Never re-resolves, no strict mode. After a re-render the node is invalid and the action fails or misses.

Better

Locator

Holds a search recipe and searches again on every action. Waits for the element to be ready and refuses to click a "random" one of several.

Figure 2. The difference is not syntax but when the search happens: once or every time.

When you need custom logic over a node, locator.evaluate() is usually enough: it also resolves the element at call time.

// bad: the node is captured once
const handle = await page.$('.price');
await handle?.click();

// good: a locator and evaluate on it
const width = await page.getByTestId('banner').evaluate((el) => el.clientWidth);

Limits. Lazy search means a mistake in a locator shows up only at the moment of the action, not at creation. getByRole alone does not guarantee uniqueness: strict mode does that at action time. Roles work only when the markup is semantic: for a <div onClick> with no role it is better to fix the app than to flee to CSS. In Cypress a similar idea lives in Testing Library (findByRole); in Selenium By.cssSelector stays the main tool and a WebElement goes stale.

Common mistakes.

  • Starting with CSS classes and XPath: the first redesign breaks tests while the app works.
  • Storing await page.$(...) in a variable: after a re-render the node is dead and the error appears far from the cause.
  • "Fixing" a strict mode violation with .first(): the test clicks the wrong thing and breaks when the order changes.
  • Using getByText for buttons: getByRole('button') also checks the role.

Check yourself

A locator is created before page.goto, and the first action comes after it. Is that a mistake?

Answer

No. A locator only stores a recipe and searches nothing. The search and the waiting happen at click(), on the page that is already open. So one locator can be created once and used after a reload or a re-render.

A test stores const el = await page.$('.row') and clicks el a second later. Why can the click fail while the equivalent locator does not?

Answer

Between the two lines the framework may have replaced the DOM node. The ElementHandle points at the old, removed node and does not search again. A locator searches anew on every action, so it finds the new node and waits for it to be ready.

In the interview. Junior: I start with getByRole and a name because that is how the user sees the element, then label and text, and I take a test id when there is no stable role. A Locator is lazy, so there is no stale element. Middle/Senior: A Locator stores a search recipe and re-resolves it on every action, and strict mode stops me from clicking a random element among several. I rarely use ElementHandle: it never re-resolves the node and a re-render invalidates it. I investigate a strict mode failure instead of muting it with first().

getByRole in depth: options and precision

getByRole finds an element in the accessibility tree by role and accessible name, not by tag or class. The name matches as a case-insensitive substring by default, and exact: true or a regex gives precision. If the element is in the DOM but getByRole cannot find it, it is often a markup defect (no label or aria-label) that should be fixed in the app.

Playwright · Locators

The button is in the DOM but getByRole cannot find it. Is it a test bug or an app bug?

A developer added an icon button "×", the test looks for getByRole('button', { name: 'Close' }) and times out although the button is visible on screen. Another test with name: 'Save' suddenly finds two buttons. Both cases come from one mechanism: getByRole does not search by tags but by the accessibility tree, and the name matches by specific rules. This lesson shows how it works, how to read a failure, and where the test's responsibility ends and an app bug begins.

How it works and why. From the DOM the browser builds a separate accessibility tree in which every element has a role (button, link, heading, textbox) and an accessible name. Screen readers read this tree, and getByRole searches it. The role comes from an explicit role attribute or is derived from the tag: <button> is a button, <a href> is a link, <h2> is a heading, <input type="checkbox"> is a checkbox. The name is built from the element's content, aria-label, aria-labelledby, an associated <label> or alt. The design decision: the locator checks what a real assistive-technology user gets, so a test also catches lost accessibility.

From the DOM to getByRole

<button aria-label="Close">DOM: an icon without text the browser builds Accessibility treerole: button, name: Close Playwright searches getByRole('button', { name })found: role and name matched <div onClick>×</div>role: generic, no name: not found Neither role nor name appears by itself:the markup provides them.
Figure 1. getByRole looks at the accessibility tree, not the DOM. What did not get a role and a name there, the locator cannot see.

How name matches. By default name is a case-insensitive substring search and whitespace is normalised. So { name: 'Save' } finds both "Save" and "Save draft". For a full match there is exact: true (case-sensitive, the whole string), for a flexible match a regex. Extra options filter by state: checked, pressed, expanded, selected, disabled, and level for headings.

page.getByRole('button', { name: 'Save' });               // substring
page.getByRole('button', { name: 'Save', exact: true });  // exact only
page.getByRole('link', { name: /^Order #\d+$/ });         // regex
page.getByRole('heading', { name: 'Cart', level: 1 });
page.getByRole('checkbox', { name: 'I agree', checked: true });
page.getByRole('button', { name: 'Menu', expanded: false });

Substring or exact match

Typical

{ name: 'Save' }

Case-insensitive substring: finds "Save" and "Save draft". Two buttons, and the action fails with a strict mode violation.

Better

{ name: 'Save', exact: true }

The whole string, case-sensitive: one button only. For text variants a regex with anchors is better.

Figure 2. Shared words in a name give several matches: set precision with an option, not with first().

Example: a test fails and we trace the cause. The close button looks like "×", and the markup is:

<button class="close">×</button>
Error: expect(locator).toBeVisible() failed
Locator: getByRole('button', { name: 'Close' })
Expected: visible
Timeout: 5000ms
Error: element(s) not found

The log (shortened) says there is no element with this role and name. The element does have the button role, but its name is "×", not "Close". This is not a locator mistake: a screen reader user hears "×" and cannot tell what the button does. The correct fix is in the app:

<button class="close" aria-label="Close">×</button>

After that getByRole('button', { name: 'Close' }) works, and the test doubles as an accessibility check. A workaround through locator('.close') would make the test green while the defect stays.

Hidden content. By default elements with display: none, visibility: hidden and aria-hidden="true" are not in the accessibility tree, and getByRole does not see them. That is convenient: a closed modal will not be found by accident. When you need such an element, includeHidden: true exists. It also explains the puzzle "the element is in the DOM but getByRole does not see it".

Aria snapshot. To check the structure of a whole block (menu, navigation, form), version 1.49 added toMatchAriaSnapshot: it compares the accessibility tree with a YAML template. Composition and order matter, exact markup does not:

await expect(page.getByRole('navigation')).toMatchAriaSnapshot(`
  - list:
    - listitem:
      - link "Home"
    - listitem:
      - link "Courses"
`);

The template can be generated from the current page state (UI Mode and codegen have an action for it), and names in it may be regular expressions.

Limits and tools. getByRole depends on markup quality: on pages without semantics (div instead of button) it is useless, and then you either fix the app or take getByTestId. Role and name do not tell two identical buttons in different blocks apart: chaining does that (the next lesson). To avoid guessing, use npx playwright codegen or the locator picker in UI Mode: they suggest the role and name. In Cypress the equivalent comes from Testing Library, while Selenium has none out of the box: people search by CSS or XPath.

Common mistakes.

  • Forgetting that name is a substring: a strict mode violation appears. Fix it with exact: true or a regex, not with first().
  • Working around a missing name with CSS: the test is green while the icon button is inaccessible to a screen reader.
  • Expecting getByRole to see a hidden element without includeHidden.
  • Writing long copy text instead of a short name or a regex: every wording change breaks the test.
  • Looking for getByRole('button') on a <div onClick>: there is no role, and that is a real accessibility defect.

Check yourself

getByRole('textbox', { name: 'Email' }) does not find a field that is visible on screen. What do you check first?

Answer

Whether the field has an accessible name: an associated <label>, aria-label or aria-labelledby. A placeholder also gives a name, but only when there is no label or title, and it disappears once text is typed, so the field needs a real label. If there is no name at all or it differs, that is an accessibility defect to fix in the app, not to bypass with CSS.

The page has the buttons "Add" and "Add to favourites". Why does { name: 'Add' } give a strict mode violation and what do you do?

Answer

Name is a case-insensitive substring, so both buttons match. You need exact: true or the regex /^Add$/. Adding first() is wrong: the test would depend on DOM order.

In the interview. Junior: getByRole finds an element by role and accessible name, and the name matches as a case-insensitive substring by default. For precision there are exact: true and a regex. Middle/Senior: It works on the accessibility tree, so "not found" often means a markup defect: a field without a label or an icon button without aria-label. I pass such things to developers instead of bypassing them with CSS. State options (checked, expanded) and includeHidden refine the search, and I check a block's structure with toMatchAriaSnapshot.

Chains, filter, has, and, or

A target among identical elements is narrowed by content and context, not by position: chained locators, filter, and and or. A chain searches for a descendant inside the matched element, while filter({ hasText }) or filter({ has }) keeps the element itself, for example the row with the right invoice. nth and first are kept for cases where the order is the requirement.

Playwright · Locators

A table has ten rows and ten "Refund" buttons. How do you click the right one without indexes?

A test has to refund invoice INV-1042. The page has ten rows, each with a "Refund" button, and getByRole('button', { name: 'Refund' }) gives a strict mode violation. The quickest "fix" is .nth(3), but tomorrow the rows are sorted differently and the test refunds someone else's invoice. This lesson is about narrowing a locator by content and context: chaining, filter, and, or, and when positional methods are still fine.

How it works and why. Every locator method returns a new locator, so they compose. A chain a.getByRole(...) searches the inner locator only inside the elements found by the outer one. filter keeps only those elements of the outer locator that match a condition. Both are lazy, like the whole Locator: nothing runs until an action or assertion. The idea is to describe the element "like a person would": "the Refund button in the row that says INV-1042". A position ("the fourth") is a description that breaks with sorting, pagination and a new row on top.

How the search area narrows

getByRole('row')10 table rows filter by content .filter({ hasText: 'INV-1042' })1 row: the row itself, not a cell chain: a descendant .getByRole('button', { name: 'Refund' })1 button: strict mode satisfied Each step describes meaning,not a place in the DOM.
Figure 1. First shrink the set with a filter, then search inside with a chain. The final locator now matches one element.

Chaining and filter at work. The typical task: find a row by its content and act inside it.

const row = page
  .getByRole('row')
  .filter({ hasText: 'INV-1042' })
  .filter({ has: page.getByRole('cell', { name: 'Paid' }) });
await row.getByRole('button', { name: 'Refund' }).click();

const active = page.getByRole('listitem').filter({ hasNot: page.getByText('Archive') });
const toasts = page.getByRole('alert').filter({ visible: true });

filter has five conditions: hasText / hasNotText (text inside, a string or a regex), has / hasNot (a descendant that matches another locator is or is not present) and visible. The locator inside has is resolved relative to the outer element, not from the document root.

What a chain returns and what filter returns

Typical

row.getByRole('cell', { name: 'Paid' })

A chain returns a descendant: the cell itself. Clicking "Refund" through it will not work.

Better

row.filter({ has: cell })

Returns the row that contains such a cell. Then we look for the button inside it.

Figure 2. A chain goes down, filter selects among the same elements. Mixing them up gives the "wrong" element.

and: an extra condition on the same element. and intersects two locators and the result must match both: page.getByRole('button').and(page.getByTitle('Subscribe')) is a button that also has the title "Subscribe". It is not a descendant search.

or: one of two states. or returns elements matching either locator. It helps when the app legitimately shows one of two variants, for example a cookies dialog or the "Continue" button right away:

const consent = page.getByRole('dialog', { name: 'Cookies' });
const proceed = page.getByRole('button', { name: 'Continue' });

await expect(consent.or(proceed).first()).toBeVisible();
if (await consent.isVisible()) {
  await consent.getByRole('button', { name: 'Accept' }).click();
}
await proceed.click();

If both elements are present, or matches two and an action gives a strict mode violation, which is why the example uses first() before the assertion. And isVisible() does not wait, so the if branch is safe only after an assertion that guarantees one of the states has appeared.

Reading the error: the locator found ten buttons

1Error: locator.click: Error: strict mode violation:
getByRole('button', { name: 'Refund' }) 2resolved to 10 elements:
3    1) <button class="refund">Refund</button> aka …
    2) <button class="refund">Refund</button> aka …
    …

Call log:
4  - waiting for getByRole('button', { name: 'Refund' })
  1. What: Playwright refuses to guess: the locator matched several elements instead of one, and click cannot tell which one is meant.
  2. How many: ten matches, one button per table row.
  3. Which: the list of matches. All the buttons are identical, only the row they sit in tells them apart.
  4. Where: the locator in the log is the same one, so the fault is that it is incomplete, not the app.

What to do

Narrow the locator by content: first the row through filter({ hasText: 'INV-1042' }), then the button inside it. Not .first() or .nth(3): after a re-sort the test clicks someone else's invoice.

Figure 3. The real error text (shortened): the numbers lead to the explanations.

Positional methods. first(), last() and nth(i) are a last resort. They depend on DOM order, which changes with sorting, pagination or a new item at the start. They are justified when order is the requirement, for example "the first in the list is the newest".

ToolReturnsExample
ChainA descendantThe Delete button in the cart
filter({ hasText })The same elementThe row with an invoice number
filter({ has })The same elementA card with a "New" badge
andMatch with bothA button with a given title
orMatch with eitherA dialog or a next button
nthBy positionOrder is the requirement

Limits. A text filter matches by substring, so hasText: 'INV-10' finds both INV-1042 and INV-1099: for precision use a word-boundary regex (/\bINV-1042\b/) or filter({ has: page.getByRole('cell', { name: 'INV-1042', exact: true }) }). If the identifier is not visible in text and the structure is complex, a test id on the row (data-testid="order-row") followed by filter is more fitting. In Selenium this lookup is written in XPath (//tr[contains(.,'INV-1042')]//button), which breaks with structure, while Playwright expresses it readably.

Common mistakes.

  • .first() against a strict mode violation: the test clicks the wrong thing and breaks when the order changes.
  • Mixing up a chain and filter({ has }): you get a descendant instead of the row.
  • or where certainty is needed: it hides app instability instead of exposing it.
  • Finding a row by index although it has unique text.
  • hasText as a plain string on similar values: it matches more than intended.

Check yourself

How does page.getByRole('row').getByRole('cell', { name: 'Paid' }) differ from page.getByRole('row').filter({ has: page.getByRole('cell', { name: 'Paid' }) })?

Answer

The first returns the "Paid" cells (descendants of rows), the second returns the rows themselves that contain such a cell. To act on a row (the "Refund" button) you need the second.

A test with consent.or(proceed).click() sometimes fails with a strict mode violation. Why?

Answer

When the dialog and the button are present together, or matches two elements and click requires one. Either handle the dialog first or check presence with first(), but do not click the union.

In the interview. Junior: I find a table row with filter and hasText, then look for the button inside the row. I use nth only when order matters. Middle/Senior: I distinguish a chain (returns a descendant) from filter({ has }) (returns the element itself), and for an extra condition and or for two legitimate states, remembering strict mode if both match. I do not use first() as a plug: I find out why there are several elements.

Test id, lists and the all() trap

all() and count() return the current state without waiting, while textContent() waits only for the element and reads it once. So a loop over all() on a still-empty list runs zero times and the test is falsely green. Collections are checked with retrying assertions: toHaveCount, toHaveText with an array. getByTestId is used when there is no stable role or text; testIdAttribute sets its attribute.

Playwright · Locators

The test is green but the list was still loading, and the loop checked nothing. How can that happen?

A test iterates over list items and checks that each has an image. It is green. Then the image is removed from one product and the test stays green. The cause is the line for (const item of await items.all()): when it ran, the list was still loading, the array was empty and the loop ran zero times. This lesson covers when getByTestId fits, how to check collections with retrying assertions, and why locator.all() is dangerous without a wait.

getByTestId and its configuration. By default getByTestId looks for the data-testid attribute. If your project uses another one, such as data-qa, set it in the config and getByTestId then uses it everywhere:

// playwright.config.ts
export default defineConfig({
  use: { testIdAttribute: 'data-qa' },
});

// in a test
await page.getByTestId('cart-badge').click();   // [data-qa="cart-badge"]
await expect(page.getByTestId('total')).toHaveText('$1,250');

A test id fits when there is no stable role and text: icons without a label, dynamic containers, repeated cards, a multilingual UI. Where a role and a name exist, getByRole is better because it also checks accessibility. A test id does not depend on copy or markup, but it must be maintained in the app, so agree on naming (order-row, not arbitrary strings).

How it works: a snapshot versus waiting. Collection assertions (toHaveCount, toHaveText with an array, toContainText) retry until the timeout while the condition is false. locator.all() takes a one-moment snapshot: it returns an array of locators for the elements that are in the DOM right now and does not wait. The same goes for count(), allTextContents() and isVisible(). textContent() and innerText() wait for the element to appear but read the text once: all of them return the value "here and now", with no retries. That is a deliberate design: such methods are for logic ("is the dialog open?") where waiting is not wanted. The danger starts when they are used as a check.

A snapshot on an empty list

List in the DOM loading: 0 3 elements all() here all() = []loop: 0 iterations, test is green With a wait toHaveCount(3)waits, retries all() = 3loop over 3 elements
Figure 1. The same code gives different results depending on when the snapshot is taken. A count assertion moves it to the moment the list is ready.

Example: a falsely green test and the fix.

// before: if the list has not loaded yet, the loop checks nothing
for (const item of await page.getByRole('listitem').all()) {
  await expect(item.getByRole('img')).toBeVisible();
}
// after: first wait for a known count
const items = page.getByRole('listitem');
await expect(items).toHaveCount(3);
for (const item of await items.all()) {
  await expect(item.getByRole('img')).toBeVisible();
}

The fix works because toHaveCount retries until the timeout and fails if the list never appears. After it, the snapshot is guaranteed to see three elements. The best version has no loop at all: "every item has an image" can be expressed with filter:

await expect(items.filter({ has: page.getByRole('img') })).toHaveCount(3);

Collection assertions. Instead of loops over elements, prefer retrying assertions:

const items = page.getByRole('listitem');
await expect(items).toHaveCount(3);
await expect(items).toHaveText(['Bread', 'Milk', 'Cheese']);  // count, order, text
await expect(items).toContainText(['Bread', 'Cheese']);       // text fragments
await expect(items).toHaveText([/Bread/, /Milk/, /Cheese/]);  // regex for each

count() or toHaveCount()

Typical

expect(await items.count()).toBe(3)

The value is read once. If the list is still loading, the test fails at once or, worse, checks a stale state.

Better

await expect(items).toHaveCount(3)

Playwright repeats the check until the timeout. The test is stable and fails only when the count is really wrong.

Figure 2. A retrying assertion replaces both the wait and the check: no separate pauses needed.

When the count is really needed for logic. When the value changes asynchronously, wrap it in expect.poll, which repeats the function until it succeeds:

await expect.poll(() => page.getByRole('listitem').count()).toBeGreaterThan(0);

Limits. toHaveText with an array checks count and order, so for a list with unstable order it will fail falsely: there you check individual elements with filter and toBeVisible. all() also has honest uses: the count is unknown in advance but the list is already stable (after await expect(spinner).toBeHidden()), or each element needs complex checks that do not fit one assertion. In Selenium the equivalent findElements also returns an empty list without an error, while Cypress cy.get retries by itself, so the trap is less visible there.

Common mistakes.

  • A loop over all() without a wait: a falsely green test on an empty list.
  • expect(await locator.count()).toBe(3) instead of toHaveCount(3): no retries.
  • Changing testIdAttribute mid-project without agreement: every getByTestId breaks.
  • A test id on everything although an accessible role exists: you lose the accessibility check.
  • toHaveText with an array for a list whose order is not guaranteed: the test is flaky.

Check yourself

Why can the loop for (const row of await rows.all()) run with no checks and leave the test green?

Answer

all() does not wait and returns the elements that are in the DOM at that moment. If the list is still loading, the array is empty and the loop runs zero times. Put an assertion that waits before it, such as toHaveCount(n).

When is getByTestId better than getByRole, and when not?

Answer

Better when there is no stable role or text: an icon without a label, a container, a card, a multilingual UI. Worse when a role and name exist: a role also checks accessibility and a test id does not.

In the interview. Junior: For lists I use toHaveCount and toHaveText with an array because they retry. all() does not wait, so I put a count assertion before it. Middle/Senior: all(), count() and textContent() take a snapshot, and on an empty list a loop gives a falsely green test. I use them for logic, not for checks, and wrap changing values in expect.poll. I take getByTestId when there is no role or text, configure testIdAttribute if needed and agree on naming with developers.