[Feature] Align getByRole behavior with testing librrary
See original GitHub issueI really like the approach of getByRole
and similar selectors in testing library and therefore I’m happy to use the in playwright too!
There is one difference that makes problems for me. Having a page like:
<button>Add</button>
<button>Add post</button>
Using the getByRole
selector in testing library would match a single result:
screen.getByRole('button', {name: 'Add'}) // Returns only the first button
While the same selector in playwright matches both and therefore fail:
page.getByRole('button', {name: 'Add'}) // Fails because it matches both buttons.
The difference between Playwright and testing library is, that Playwright uses a contains query if a string is passed as the name, while testing library is using an exact match. In testing library there is an exact
option to toggle this behavior, which defaults to true
. In both libraries you can use RegEx to perform contains or other matches.
There is currently a workaround that I’m using for an exact match:
page.getByRole('button', { name: /^Add$/ })
Even though it is a behavior change, I would vote for aligning the behavior of the selectors, especially as they claim to be like testing library. That makes it a lot easier for devs to switch from one library to another.
Issue Analytics
- State:
- Created 10 months ago
- Comments:6 (5 by maintainers)
Yes it is different. I will let @dgozman give a better explanation to why we chose the exact default to be false
Would assert if, or as Playwright is a test library, being exact is more important and should be the default behavior. Or better? Provide both by doing:
page.getByRole(‘button’, {nameExact: ‘Add’}) page.getByRole(‘button’, {nameContains: ‘Add’}) page.getByRole(‘button’, {nameExactIgnoreCase: ‘Add’}) page.getByRole(‘button’, {nameContainsIgnoreCase: ‘Add’})
Remove ‘name’ and only have the fully qualified match behavior…?
Also would assert “name == name”, and “name != name*”. Or again why is it most every library out there has Equals and/or Contains/ContainsIgnoreCase… Seems strange lax/contains would be the default and add confusion… If one wants a lax match, easy enough with a regex too?
Also locators are strict by default. Just saying the precedence in the library is more of a strict nature. Not a bad thing, if users know they must be exact, would argue that increases the quality of the testing?