Test Automation Stack

,

Cypress: Adding a Custom Command

Cypress provides this great feature of adding custom commands, using which one can add repeatable code or functionality as Custom command.

If you are new to cypress, in cypress commands are nothing by when you type cy. there are functions available like cy.get() cy.contains() . These are the cypress inbuilt commands. By using Custom commands, we can create our own new command and attach the command to cy object.

To start

Navigate to support folder and open commands.ts/js file

Add your new custom command like below example





Cypress.Commands.add(“scrollAndGetText”, (selector: string) => {

cy.scrollTo(“bottom”, { duration: 3000 })

return cy.get(selector).invoke(“text”)

})

The work is not done yet, all we did is added a custom command in commands file.

We also need to let cypress know that this is the new custom command added and cypress should show this custom command when we type cy.

For letting cypress know about this new custom command to chain with cy object

Navigate to support folder and open index.js/ts file

Add the new custom command under Chainable interface like below





declare global {

namespace Cypress {

interface Chainable {

scrollAndGetText(selector: string)

}

}

}

After this, if you go back to your cypress test and type cy. and type starting letters of your new custom command, cypress will show the newly added command like below

Leave a comment

I’m Gurudatt

Profile Pic

With over 12 years of quality assurance experience, i have used various test automation tools and testing concepts and helped organization and teams to speed up testing process effectively. I’m also a Cypress.io Ambassador and BrowserStack Champion.

Let’s connect

Discover more from Test Automation Stack

Subscribe now to keep reading and get access to the full archive.

Continue reading