Cypress Custom Commands

Profile picture for user arilio666

Cypress can add custom commands with its API and override existing commands.

Syntax:

Cypress.Commands.add(name, callbackFn)
Cypress.Commands.add(name, options, callbackFn)
Cypress.Commands.addAll(callbackObj)
Cypress.Commands.addAll(options, callbackObj)
Cypress.Commands.overwrite(name, callbackFn)

Arguments:

Name argument comprised of string used to provide our very own custom name.
callbackFn is used to pass in the function that receives arguments passed to the command.
callbackObj is an object with a callback function as properties.

Correct Usage:

Cypress.Commands.add('login', (email, pw) => {})
Cypress.Commands.addAll({
 login(email, PW) {},
 visit(orig, URL, options) {},
})
Cypress.Commands.overwrite('visit', (orig, url, options) => {})

Example:

For example, we will use our programsbuzz login page to add a username and password as a custom command.

Go to your support/command.js file and add the following.

Cypress.Commands.add('userName', (uname) => {
   cy.xpath("//input[@id='edit-name']").type(uname)
 })
Cypress.Commands.add('passWord', (pass) => {
   cy.get('#edit-pass').type(pass)
 })

Now, after adding the locators and functions, it will perform by passing arguments to type in the value.

Go to your spec file.

describe('Type Command',()=>{
   before(() => {
       cy.visit('https://www.programsbuzz.com/user/login')
       
       })
       it('Type Username And Password',()=>{
           cy.get('form').within(()=>{
               cy.userName('Ashman')
               cy.passWord('shazam@123')
               
                    
          })
       })
})

Using the custom name given, we can now pass in the value, which will provide the value into the locator present in the command.js file.

We can see that the test has passed using the custom command.

Conclusion:

This is how we can use custom commands effectively on cypress.