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
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

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.