You may already know that it's a good practice in Cypress to use data-*
attributes (e.g., data-test
, data-cy
) for targeting elements.
TIL about two super useful custom selectors that can be added, to avoid always
having to write [data-test="sign-up"]
:
getBySel
yield elements withdata-test
attribute that matches a specified selectorgetBySelLike
yield elements with adata-test
attribute that contains a specified selector
To use these selectors in your tests, first add them as commands:
Cypress.Commands.add("getBySel", (selector, ...args) => {
return cy.get(`[data-test=${selector}]`, ...args);
});
Cypress.Commands.add("getBySelLike", (selector, ...args) => {
return cy.get(`[data-test*=${selector}]`, ...args);
});
Then, use them as so:
cy.getBySel("sign-up").click();
cy.getBySel("sign").click();
Source: