Playwright Strict Mode Violation: Read the Error, Then Fix the Locator
If you have written more than a handful of Playwright tests, you have probably met this message in a red stack trace: locator.click: Error: strict mode violation: getByRole('button', { name: 'Add to cart' }) resolved
If you have written more than a handful of Playwright tests, you have probably met this message in a red stack trace:
locator.click: Error: strict mode violation: getByRole('button', { name: 'Add to cart' }) resolved to 3 elements:
1) <button>Add to cart</button> aka getByRole('listitem').filter({ hasText: 'Blue MugAdd to cart' }).getByRole('button')
2) <button>Add to cart</button> aka getByRole('listitem').filter({ hasText: 'Green MugAdd to cart' }).getByRole('button')
3) <button>Add to cart</button> aka getByRole('listitem').filter({ hasText: 'Red MugAdd to cart' }).getByRole('button')
That output is real. I produced it on purpose with a tiny product list page and Playwright 1.63 so we can walk through what it means and how to fix it properly, without reaching for .first() every time.
What "strict" actually means
Playwright locators are lazy. A locator is a description of how to find something, and it only touches the DOM when you act on it. When the action needs exactly one target (click, fill, check, hover, textContent and friends), Playwright insists that the description matches exactly one element. If it matches two or more, it refuses to guess and throws the strict mode violation.
Actions that are naturally about many elements are fine. count(), all() and allTextContents() happily work on a locator that resolves to several nodes. So the error is not saying "your locator is broken". It is saying "your locator is ambiguous for this particular action".
That is a feature. A test that silently clicks the first matching button keeps passing after someone reorders the page, and then it is testing the wrong thing.
The demo page
Here is the markup I used. It has the two patterns that cause most strict mode errors in real apps: repeated buttons inside cards, and the same link in two landmarks.
<header><nav><a href="/cart">Cart</a></nav></header>
<main>
<ul id="products">
<li class="card"><h3>Blue Mug</h3><button>Add to cart</button></li>
<li class="card"><h3>Green Mug</h3><button>Add to cart</button></li>
<li class="card"><h3>Red Mug</h3><button>Add to cart</button></li>
</ul>
<p id="status"></p>
</main>
<footer><a href="/cart">Cart</a></footer>
A small script writes "Green Mug added" (or whichever product) into #status when a button is clicked, so we can prove which button each fix hits.
Read the error before you fix it
The most useful part of the message is the aka line under each match. Playwright suggests a unique locator for every element it found. For the duplicated cart link, it printed:
1) <a href="/cart">Cart</a> aka getByRole('navigation').getByRole('link', { name: 'Cart' })
2) <a href="/cart">Cart</a> aka getByRole('contentinfo').getByRole('link', { name: 'Cart' })
So Playwright is already telling you the structural difference between the two: one lives in the navigation landmark, the other in the footer (contentinfo). You do not have to copy the suggestion literally, but it points at the right fix.
Fix 1: scope to the container that makes the element unique
Ask yourself what a human would use to tell the elements apart. For the cart link, it is "the one in the top navigation".
await page.getByRole('navigation').getByRole('link', { name: 'Cart' }).click();
Chaining locators narrows the search to descendants of the first match. In my run this resolved to exactly one element. Landmarks such as navigation, main, dialog and contentinfo are excellent scopes because they rarely change and they reflect how users read the page.
Fix 2: filter the repeated item by its text
For product cards, the distinguishing fact is the product name. filter({ hasText }) keeps only the list items that contain that text, then you look for the button inside it:
await page
.getByRole('listitem')
.filter({ hasText: 'Green Mug' })
.getByRole('button', { name: 'Add to cart' })
.click();
After this click, #status read "Green Mug added", so the right card was used.
Fix 3: filter by a child locator instead of raw text
hasText matches anywhere inside the element, which can be too loose if a description paragraph mentions another product. filter({ has }) lets you require a specific child element instead:
await page
.getByRole('listitem')
.filter({ has: page.getByRole('heading', { name: 'Red Mug' }) })
.getByRole('button')
.click();
This one only matches the card whose heading is "Red Mug". The status line confirmed "Red Mug added".
Fix 4: make the accessible name match exactly
A sneaky cause of strict mode errors is substring matching. By default, the name option of getByRole matches case-insensitively and as a substring. On a page with "Save" and "Save draft" buttons:
await page.getByRole('button', { name: 'Save' }).count(); // 2
await page.getByRole('button', { name: 'Save', exact: true }).count(); // 1
await page.getByRole('button', { name: /^save$/i }).count(); // 1
Both exact: true and an anchored regular expression removed the ambiguity in my test. Use whichever reads better to your team.
Fix 5: add a test id when the UI gives you nothing else
Sometimes the visible UI really has no stable difference, for example an icon-only button repeated in a data grid. In that case, agree with the developers on a data-testid attribute and use getByTestId:
await page.getByTestId('publish').click();
Playwright's own docs prefer user-facing locators (role, label, text) first, so treat test ids as the fallback, not the default.
What about first(), last() and nth()?
They work, and they switch off the strictness check by telling Playwright which match to take. The Playwright documentation explicitly does not recommend them, because when the page changes you may end up clicking an element you never intended. My rule of thumb: use them only when position is the thing under test, such as "the newest row is at the top of the table". In that case, write a comment saying so.
Strict mode in reads and assertions
The error is not limited to clicks. In the same demo, this line failed too:
await page.getByRole('heading').textContent(); // strict mode violation, 3 elements
If you really want every heading, ask for every heading:
const names = await page.getByRole('heading').allTextContents();
// [ 'Blue Mug', 'Green Mug', 'Red Mug' ]
In the test runner, prefer web-first assertions that are built for lists, such as await expect(page.getByRole('listitem')).toHaveCount(3), instead of reading text and comparing by hand.
A quick debugging checklist
When the error shows up in CI, work through these in order:
- Read every
akasuggestion in the error. It usually names the container that separates the matches. - Check whether a modal, toast or hidden duplicate (mobile and desktop menus rendered together) is adding matches.
- Check for substring name matching and add
exact: trueif needed. - Scope to a landmark or filter by the repeated item's content.
- Only then consider a test id, and keep
first()andnth()for cases where order is the requirement.
If you are still getting comfortable with locators and the test runner, this beginner-friendly Playwright walkthrough builds a small suite from scratch and covers the locator API in more depth.
Strict mode feels strict, but it is doing what a careful reviewer would do: refusing to let a vague selector pass. Every time you fix one of these errors with a better scope instead of an index, your suite becomes easier to read and harder to break.
Written by the editorial team at Tutorials Mania, where we also run instructor-led sessions on Playwright test automation.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.