How to Overwrite Commands in Cypress
To overwrite commands in Cypress, we can use Cypress.Commands.overwrite
, passing the name of the command we want to override as a string:
Cypress.Commands.overwrite('get', (fn, selector) => {
if (selector.startsWith('$')) {
selector = `[data-testid="${selector.substring(1)}"]`;
}
return fn(selector);
});
Add the above code to your commands.js
file inside your support
folder. This code will overwrite the built-in get
function. Now if the selector starts with a dollar sign, it will replace the selector to use a data-testid
selector instead.
When you overwrite a command, make sure you always return the function that is passed as a parameter. This references the original Cypress function. Now we can use this command inside the test cases like we normally would:
cy.get('$featured');
cy.get('[data-testid="featured"]');
Thanks to the custom command we've defined, the above two calls will be the same. You can also add new custom commands by calling add
instead of overwrite
:
Cypress.Commands.add('login', (email, password) => { ... });
Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: