[TIL] Cypress custom selector commands
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"]:
getBySelyield elements withdata-testattribute that matches a specified selectorgetBySelLikeyield elements with adata-testattribute 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: