mgrubinger / blog

https://www.grooovinger.com/
MIT License
0 stars 0 forks source link

The single most effective Cypress trick to improve accessibility #46

Open mgrubinger opened 3 weeks ago

mgrubinger commented 3 weeks ago

short: Find and fix accessibility issues while writing Cypress tests.

(Sorry for the stupid clickbaity title πŸ˜ƒ)

tl; dr

By selecting elements based on their accessible role and name using Cypress Testing Library, we effortlessly found accessibility issues while authoring Cypress tests.


Cypress Testing Library is a plugin for Cypress that adds a bunch of additional commands to Cypress. The one I find most effective is findByRole.

By using findByRole() as much as possible (versus selecting elements based on class, id or data-test-id), we caught a ton of accessibility issues while authoring tests.

We found some elements that had a wrong role, like interactive elements that had non-interactive roles (think: divs as buttons etc).

We also found many elements where the accessible name of an element did not describe what sighted users would see. An example would be a "close" button that also included an icon name in the accessible name.

As an additional benefit, you get to write tests by thinking about how your users would interact with the page. An example would be:

"click on the button that reads 'login'"
vs
"click on the button with the test-id data-test-id="login""

This way, if classes or ids change (and they will!) your cypress tests will no longer break. But if the text content of an element is changed, your test should and will fail.

Overall this helped us write more natural tests while at the same time catching accessibility issues along the way. Highly recommended.

Side note: if you use Playwright instead of Cypress, you can use getByRole which does the same thing.