How to Overwrite Commands in Cypress

How to Overwrite Commands in Cypress

Ferenc Almasi β€’ 2021 October 20 β€’ Read time 1 min read
  • twitter
  • facebook

To overwrite commands in Cypress, we can use Cypress.Commands.overwrite, passing the name of the command we want to override as a string:

Copied to clipboard! Playground
Cypress.Commands.overwrite('get', (fn, selector) => {
    if (selector.startsWith('$')) {
        selector = `[data-testid="${selector.substring(1)}"]`;
    }

    return fn(selector);
});
commands.js

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:

Copied to clipboard!
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:

Copied to clipboard!
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:

Learn Cypress with Educative
How to Overwrite Commands in Cypress
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

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:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.