Learn how to query elements the way your users perceive them, with no plugin.
For years, when someone asked me how to find elements by their role in Cypress, my answer was the same: install Cypress Testing Library.
That's no longer needed. Since Cypress 16.2.0, cy.getByRole() ships with Cypress itself.
But you might be wondering: why would I find an element by its role?
Because that's how your users find it. Nobody sees [data-test="save-button"] on a page. A sighted user sees a button that says "Save", and a screen reader user hears "Save, button". When the test looks for the same thing, it also tells you when that button stops being a button, or stops having a name, which is a real accessibility bug.
That's precisely what I will show you in this pinch of Cypress.
The page
Let's imagine the following settings page.
<h1>Settings</h1>
<nav aria-label="Settings">
<a href="/profile">Profile</a>
<a href="/billing" aria-current="page">Billing</a>
</nav>
<form>
<label for="email">Email</label>
<input id="email" type="email" />
<label>
<input type="checkbox" />
Send me the newsletter
</label>
<button type="submit">Save</button>
</form>
<div role="alert"></div>
When the form is saved, the alert shows "Changes saved".
The test
describe('Settings', () => {
beforeEach(() => {
cy.visit('/settings')
})
it('saves the email and the newsletter preference', () => {
cy.getByRole('textbox', { name: 'Email' })
.type('walmyr@example.com')
cy.getByRole('checkbox', { name: 'Send me the newsletter' })
.check()
cy.getByRole('button', { name: 'Save' })
.click()
cy.getByRole('alert')
.should('have.text', 'Changes saved')
})
})
Now, let's understand what this code does.
First, cy.getByRole('textbox', { name: 'Email' }) finds the email field. An <input type="email"> has the textbox role, and its accessible name comes from the <label> pointing at it.
Then, the checkbox is found the same way. Its name comes from the text inside the <label> that wraps it.
After that, we click the button named "Save". Its name is its own content.
Finally, cy.getByRole('alert') finds the status message, and .should() waits until it has the expected text. Like cy.get(), cy.getByRole() is a query, so Cypress retries it until the element exists and every chained assertion passes, up to defaultCommandTimeout.
Notice that there's not a single CSS selector in the test.
Note: I still like data-test attributes, and I'm not telling you to replace all of them. But when what matters is how an element is exposed to the user, a role and a name tell you much more than an attribute that only exists for the test.
Everything okay so far? Then let's look at the details.
How the name is matched
The name option accepts a string, a number, a regular expression, or a function.
A string must match the whole accessible name, and the comparison is case-sensitive (whitespace is collapsed and trimmed first). So { name: 'Save' } does not find a button named "Save changes".
When you want a partial match, use a regular expression.
cy.getByRole('button', { name: /^delete/i })
.should('have.length', 2)
The accessible name comes from the element's content, a <label>, aria-label, aria-labelledby, an image's alt, or title. Content marked aria-hidden="true" and CSS ::before and ::after content are left out.
Scoping the search
You can chain cy.getByRole() off any command that yields DOM elements. In that case, it only searches inside that subject.
cy.get('nav')
.getByRole('link')
.should('have.length', 2)
It also works inside .within(), which reads really nice with a dialog.
cy.getByRole('dialog', { name: 'Delete user' }).within(() => {
cy.getByRole('button', { name: 'Delete' }).click()
})
What about checked, selected, or level?
If you come from Testing Library, you might try { checked: true } or { level: 2 }. cy.getByRole() doesn't accept them. Any option it doesn't know throws an error.
Instead, you narrow the result with .filter().
cy.getByRole('link')
.filter('[aria-current="page"]')
.should('have.text', 'Billing')
cy.getByRole('checkbox')
.filter(':checked')
.should('have.length', 1)
At first I found it a bit strange, but it makes sense. cy.getByRole() yields every match, in document order, and the rest is plain Cypress that you already know.
Native elements first
This is the part I like the most.
By default, for roles that HTML has an element for, cy.getByRole() only matches the native element. So, a <div role="button"> is not found by cy.getByRole('button').
If your application (or your component library) really needs it, use the native option.
cy.getByRole('button', { name: 'Cancel', native: false })
.click()
Why do I like this default? Because a <div> pretending to be a button is often where the keyboard bugs live. Having to write native: false makes you stop and think about it.
Note: Roles that HTML has no element for, such as tab or alert, are matched through the role attribute without any extra option. That's why cy.getByRole('alert') worked in the test above.
Note 2: By default, elements hidden from the accessibility tree are skipped (the hidden attribute, aria-hidden="true", display: none, or visibility: hidden). To include them, pass { hidden: true }.
When it fails
When nothing matches, the error tells you what Cypress found instead.
Timed out retrying after 4000ms: Expected to find an accessible native element with the role "button" and name "Svae", but never did.
Below that message, it lists the roles and names it did find on the page. A typo like the one above is solved in seconds.
Coming from Cypress Testing Library?
cy.getByRole() covers what findByRole() and findAllByRole() did for role queries. The migration is mostly about the state options.
// Before
cy.findByRole('tab', { selected: true })
.should('have.text', 'Billing')
// After
cy.getByRole('tab')
.filter('[aria-selected="true"]')
.should('have.text', 'Billing')
If no other Testing Library query is left in your project, you can remove @testing-library/cypress from the dependencies, its import from the support file, and its types from tsconfig.json. One dependency less. 🎉
Attention: If your project already has a custom command called getByRole, it now errors. Rename it.
That's it!
To sum up:
- Upgrade to Cypress 16.2.0 or later.
- Find elements by role and accessible name, the way your users find them.
- Use
.filter()for states. - Prefer native elements, and use
native: falseonly when you need it.
For all the options, check the official cy.getByRole() documentation.
I hope you learned something new. Did you like the content? Leave a comment, and let's talk.
Want to go deeper?
At the Talking About Testing School, you'll find hands-on courses where you learn by writing real tests, not by watching passive tutorials.
- New to Cypress? Start with Cypress Basics, which is free.
- Want to find accessibility issues with Cypress? Bruno Pulis teaches you how in The 6 Most Common Accessibility Issues, with Cypress and axe-core, and goes through the standard in the WCAG 2.2 Level A and Level AA courses. All three are in the Accessibility Bundle.
- Want to master Cypress? The Cypress Mastery Bundle has six Cypress courses, from the fundamentals to agentic testing with Cypress Tap.
And it's Black November! Until November 30, every course and every bundle is 40% off. The code to enter at checkout is on the site.
Every paid course has a free preview lesson and a 14-day money-back guarantee, so you can try it without risk.
👉 Come learn with us at the TAT School!
Until next time, and happy testing! 👋
Top comments (1)
The native: false example is where I would add an explicit keyboard check. A div with role="button" can match by role and name without handling Enter or Space. For the Cancel control, would you include focus returning to the Delete user dialog's trigger after it closes, alongside the successful click assertion?