Search
⌘K
    to navigateEnterto select Escto close

    Custom Commands in Cypress

    • In Cypress, a user can create a new command or overwrite an existing command. These are called as custom commands.
    • These custom commands are used to create the test steps that are repeated in an automation flow.
    • The custom commands can be created in cypress/support/commands.js.

    Let's see some examples of custom command for login :

    1import { loginPath } from "Constants/routes";
    2
    3const authHeaders = {
    4  Authorization: `Token ${Cypress.env("AUTH_TOKEN")}`,
    5};
    6
    7Cypress.Commands.add("loginViaUI", (username, password) => {
    8  cy.get("[data-cy='login-email-field']").type(username);
    9  cy.get("[data-cy='login-password-field']").type(password);
    10  cy.get("[data-cy='submit-button']").click();
    11});
    12
    13Cypress.Commands.add(
    14  "login",
    15  (email = "oliver@example.com", password = "welcome", path = "/") => {
    16    cy.request({
    17      url: loginPath,
    18      method: "POST",
    19      form: true,
    20      body: {
    21        user: {
    22          email: email,
    23          password: password,
    24        },
    25      },
    26      headers: {
    27        Accept: "application/json",
    28        ...authHeaders,
    29      },
    30    });
    31    cy.visit(path);
    32  }
    33);
    34
    35Cypress.Commands.add(
    36  "loginAndVisit",
    37  (path = "/", email = "oliver@example.com", password = "welcome") => {
    38    cy.login(email, password, path);
    39  }
    40);

    Both the custom commands i.e. loginViaUI and login are used for different purposes. For testing the login functionality we use the loginViaUI command. Please note that the command loginViaUI here is just for an example. We don't need to create it as a command always unless it's needed in many places.

    In most of the web applications, the user need to be logged in. If we write tests using loginViaUI, for every test it's going to take much more time to run the tests. So, we use login custom command which will skip the UI and log in programmatically via request.

    Let's take another test step that is often repeated in the automation flow:

    1Cypress.Commands.add("clearAndType", (selector, text = "") => {
    2  cy.get(selector).clear().type(text);
    3});
    4
    5cy.clearAndType("[data-cy='login-email-field']", "a-random-email@gmail.com");

    This custom command clears out the previously written text and then typing the new text inside any text field.

    Previous
    Next