Cypress - Custom Commands


Cypress custom commands are described by users and not the default commands from Cypress. These customized commands are used to create the test steps that are repeated in an automation flow.

We can add and overwrite an already pre-existing command. They should be placed in the commands.js file within the support folder present in the Cypress project.

Cypress Project Command

Syntax

The syntax for the custom commands in Cypress is as follows −

Cypress.Commands.add(function-name, func)

Cypress.Commands.add(function-name, opts, func)

Cypress.Commands.overwrite(function-name, func)

Here,

  • function-name is the command that is being added/overwritten.

  • func is the function passing that gets arguments passed to command.

  • opts is used to pass an option to describe the implicit characteristics of custom command. It is also used to determine how to handle a prior yielded subject (only applicable to Cypress.Commands.add()) and default value of option is false. The option prevSubject accepts false to ignore prior subjects, accepts true to accept prior subject and accepts optional to either begin a chain or utilize a pre-existing chain. An option accepts string, array, or Boolean.

Implementation of custom command

Given below is the implementation of custom command in commands.js

Cypress.Commands.add("userInput", (searchTxt) => {
   //to input search text in Google and perform search
   cy.get("input[type='text']").type(searchTxt);
   cy.contains("Google Search").click();
});

Implementation of Actual Test

Given below is the implementation of actual test in Cypress with custom command −

describe('Tutorialspoint Test', function () {
   // test case
   it('Test Case 6', function (){
      // launch the application
      cy.visit("https://www.google.com/");
      //custom parent command
      cy.userInput('Java')
   });
});

Execution Results

The output is as follows −

Implementation of Actual Testing

The output logs show the custom command – userInput (having get, type and click commands) getting executed.

It is recommended that a custom command should not be too lengthy. It should be brief,because, adding too many actions within a custom command tends to show the execution.

Advertisements