Cypress Testing Library
We started to use the Cypress Testing Library whenever possible to have more reliable selectors since the Testing Library simulates how an end-user would navigate through the website. This section aims to explain why we decided to use Testing Library and how we do to find the selector and apply them to our tests.
#
Why?We've noticed that some of our selectors were unstable with the new skin for Neve, and as a result, some of our tests were failing. The Testing Library aims to provide a selector that doesn't change when the implementation changes, only when the functionality of a part of the Web UI changes; this makes our tests easier to maintain once we get the hang of using those selectors.
#
How do we do it?It's important to remember that not every element in the UI is selectable using the testing library selector due to not every element being interactive due to accessibility issues or how WordPress implements it. We will still use it as CSS selectors for those cases.
The easier way to find a selector is using the Testing Playground extension available for Chrome and Firefox Browser.
For the example on the GIF below, if you want to click on the Browse Free Themes
button, you will use this code cy.findByRole('button', { name: /browse free themes/i }).click();
Sometimes the browser extension may fail to show the correct selector; in that scenario, we can still use the findByRole
selector if we find the selector manually.