DEV Community

Cover image for Switching to cypress-testing-library
Álvaro Martínez
Álvaro Martínez

Posted on • Updated on

Switching to cypress-testing-library

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>
Enter fullscreen mode Exit fullscreen mode

And then in my cypress test I would look for the element using

cy.get('[data-cy="submit"]'); // [...]
Enter fullscreen mode Exit fullscreen mode

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'
});
Enter fullscreen mode Exit fullscreen mode

2) Replacing every relevant cy.get with cy.findByTestId among the existing test files

Note: I'm only covering cy.get() to cy.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"]')
Enter fullscreen mode Exit fullscreen mode

with

cy.findByTestId('something')
Enter fullscreen mode Exit fullscreen mode

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 😅

Boromir meme 'one does not simply REGEX'

Latest comments (0)