Recently I began using cypress-testing-library to enhance my cypress tests.
Following cypress best practices, I used to add a data-cy="something"
attribute to any element I wanted to select with cypress.
<button data-cy="submit" type="submit">Submit</button>
And then in my cypress test I would look for the element using
cy.get('[data-cy="submit"]'); // [...]
When I added cypress-testing-library
to the project, I had two problems to solve:
1) Changing the testId attribute
The default testId used by cypress-testing-library is data-testid
, not data-cy
. Luckily this can be changed as explained in the documentation:
cy.configureCypressTestingLibrary({
testIdAttribute: 'data-cy'
});
2) Replacing every relevant cy.get
with cy.findByTestId
among the existing test files
Note: I'm only covering
cy.get()
tocy.findByTestId()
conversion, but the same approach would be valid for other cypress/cypress-testing-library commands.
I wanted to replace every
cy.get('[data-cy="something"]')
with
cy.findByTestId('something')
Luckily, VS Code
search & replace allows using regular expressions & capture groups, and I was able to replace all occurences using the following regex:
find: cy\.get\('\[data-cy="(\w.+)"\]'
replace: cy.findByTestId('$1
'
Disclaimer: not a regex expert 😅
Top comments (0)