CodePark/ questions / Testing accessibility
START PRACTICINGPRACTICE
Frontend question · Accessibility › Testing accessibility

This test fails with "Unable to find an accessible element with the role 'button' and name /save/i", even though the button is on screen. What is the right fix?

// Component
<button onClick={save}><SaveIcon /></button>

// Test
screen.getByRole("button", { name: /save/i });
Give the button an accessible name, such as aria-label="Save" or visually hidden text

The test found a real bug. The button has no accessible name, so a screen reader would only say "button". getByRole queries roles and names in roughly the way assistive technology sees them. That is why Testing Library recommends it first. Adding aria-label="Save" fixes the user's problem and the test.

"Switch to getByTestId" is the tempting wrong answer. It makes the test pass but hides the bug.
getByText fails too, because there is no text. A <button> already has the button role.