THE REPLACEQA BLOG

Playwright getByRole vs getByTestId: choose a locator contract

Choose role, label and test-ID locators deliberately, scope repeated controls, and verify that a stable selector still checks the right behavior.

Use getByRole when the control's role and accessible name are part of the experience you want to verify. Use getByTestId when you need an explicit, stable automation identifier that does not depend on changing copy. Neither choice removes the need to assert the correct result after an action.

A question in this Reddit locator discussion asks whether role locators are really more resilient than test IDs. Resilience is incomplete without specifying what changes should break the test. A renamed button, a removed accessible name and a harmless CSS refactor should not necessarily receive the same treatment.

Decide which changes matter

Consider a template catalog with a “Save template” button. If the visible text changes to “Bookmark” with an approved design change, a test based on the old accessible name will need updating. That is maintenance, but it may also be useful review pressure: the test identifies a change to the customer-facing interaction.

A stable test ID can survive that rename. It can also survive an accidental loss of labeling. You should then verify the label separately if it matters to the requirement.

LocatorGood fitReview when…
getByRole('button', { name: 'Save template' })A named action customers recognizeCopy, semantics or accessible name changes
getByLabel('Email')A labeled form fieldLabel association or wording changes
getByTestId('template-save')Explicit automation contract across translationsID is removed, duplicated or reassigned
Scoped textA known visible item within a specific regionSimilar text appears in multiple places
CSS structureA deliberate structural requirementDOM nesting or presentation changes

The official locator guide recommends user-facing attributes and explicit contracts. It also explains strictness: an action that expects one element should not silently choose among several matches. These recommendations were checked on November 18, 2026.

Scope repeated actions to the right item

Suppose every catalog card contains an “Open” button. Selecting the third button couples the journey to sorting rather than identity. A harmless new card can redirect the test to the wrong template.

This illustrative test fragment scopes the control to an article containing the selected heading:

const card = page.getByRole('article').filter({
  has: page.getByRole('heading', { name: 'Weekly review', exact: true }),
});
await expect(card).toHaveCount(1);
await card.getByRole('button', { name: 'Open', exact: true }).click();
await expect(page).toHaveURL(/\/templates\/weekly-review$/);

The hypothetical app must actually expose cards as articles for that locator to be appropriate. Do not add misleading ARIA roles only to satisfy a test. If a card lacks a suitable semantic container, an intentional test ID on the container can be a reasonable alternative.

Use .nth() when position is itself the requirement, such as verifying the first ranked result. Document the sorting and fixture assumptions. Do not use it merely to suppress a strictness error.

Test IDs do not bypass click safety

One misleading argument in locator debates is that a test-ID click can interact with any hidden DOM element. The normal locator action still performs actionability checks, regardless of whether you found it by role, test ID or CSS. Selector choice and interaction readiness are different questions.

force: true and DOM evaluation change the interaction model. They can be useful for narrowly justified cases, but should not become a routine response to an obscured or disabled button. A customer may be blocked by exactly the condition the test is bypassing.

For a test-ID contract that also checks labeling:

const save = page.getByTestId('template-save');
await expect(save).toHaveAccessibleName('Save template');
await save.click();
await expect(page.getByRole('status')).toHaveText('Template saved');

The final assertion is a proposed app contract. For important persistence, reopen the saved item or inspect a trusted read endpoint too. A toast can appear even when storage failed.

Handle translation and changing content deliberately

For localization coverage, choose the locale explicitly and assert expected translated copy. For behavior that should stay identical across locales, test IDs can reduce repeated locator translations, while a smaller dedicated suite verifies the names and language rules.

For user-generated titles, capture the selected identity and follow it through the journey. Do not hardcode production text that changes daily, and do not use whatever text appears after navigation as its own expected value. The dynamic-content guide explains that distinction.

Review locator changes like requirement changes

When a test breaks, inspect the page and ask whether the interaction still represents the same task. Updating a selector because the approved label changed is different from pointing it at an unrelated button just to regain a pass.

A useful review experiment is to duplicate the action, reorder the cards, and intentionally point one card at the wrong destination in a controlled fixture. The test should remain stable for irrelevant ordering and reject ambiguous or incorrect behavior. This is the same principle used to verify generated tests: readable source and a green run are only the start of the evidence.

Keep checking your important customer journeys.

Explore ReplaceQA ↗