Cypress Commands & Custom Commands: 21 Important Facts

Cypress Cy Commands

anysnap 01 oct 2021 at 4 03 59 pm

Cypress is a powerful testing framework that allows developers to automate end-to-end tests for web applications. One of the key features of Cypress is its extensive set of built-in commands, which make it easy to interact with elements on a web page. In addition to these built-in commands, Cypress also allows you to create custom commands, which can further enhance the capabilities of your tests. In this section, we will explore some of the most commonly used Cypress custom commands.

Cypress Click Command

The Cypress click() command is used to simulate a user clicking on an element on a web page. This command is particularly useful when you want to interact with buttons, links, or any other clickable element. To use the click() command, you simply need to provide a selector that identifies the element you want to click. Cypress will then simulate a click event on that element.

Here’s an example of how you can use the click() command in Cypress:

javascript
cy.get('button').click();

In this example, the get() command is used to locate a button element on the page, and then the click() command is used to simulate a click on that button.

Cypress Double Click Command

The Cypress dblclick() command is similar to the click() command, but it is specifically used to simulate a double click event on an element. Double clicking is often used to trigger certain actions or behaviors on a web page. To use the dblclick() command, you need to provide a selector that identifies the element you want to double click.

Here’s an example of how you can use the dblclick() command in Cypress:

javascript
cy.get('.element').dblclick();

In this example, the get() command is used to locate an element with the class “element” on the page, and then the dblclick() command is used to simulate a double click on that element.

Cypress Right Click Command

The Cypress rightclick() command is used to simulate a right click event on an element. Right clicking often opens a context menu with additional options or actions for the user to choose from. To use the rightclick() command, you need to provide a selector that identifies the element you want to right click.

Here’s an example of how you can use the rightclick() command in Cypress:

javascript
cy.get('#element').rightclick();

In this example, the get() command is used to locate an element with the id “element” on the page, and then the rightclick() command is used to simulate a right click on that element.

Cypress Type Command

The Cypress type() command is used to simulate typing text into an input field or textarea on a web page. This command is particularly useful when you want to test form inputs or search functionality. To use the type() command, you need to provide a selector that identifies the input field or textarea, and then provide the text you want to type.

Here’s an example of how you can use the type() command in Cypress:

javascript
cy.get('input[name="username"]').type('JohnDoe');

In this example, the get() command is used to locate an input field with the name “username” on the page, and then the type() command is used to simulate typing the text “JohnDoe” into that input field.

Cypress Clear Command

The Cypress clear() command is used to clear the text from an input field or textarea on a web page. This command is often used in conjunction with the type() command to clear any existing text before typing new text. To use the clear() command, you need to provide a selector that identifies the input field or textarea.

Here’s an example of how you can use the clear() command in Cypress:

javascript
cy.get('input[name="username"]').clear();

In this example, the get() command is used to locate an input field with the name “username” on the page, and then the clear() command is used to clear any existing text from that input field.

Cypress Check Command

The Cypress check() command is used to check a checkbox or radio button on a web page. This command is particularly useful when you want to test the selection of options or choices. To use the check() command, you need to provide a selector that identifies the checkbox or radio button.

Here’s an example of how you can use the check() command in Cypress:

javascript
cy.get('input[type="checkbox"]').check();

In this example, the get() command is used to locate a checkbox element on the page, and then the check() command is used to check that checkbox.

Cypress Select Command

The Cypress select() command is used to select an option from a dropdown menu on a web page. This command is particularly useful when you want to test the selection of options from a dropdown. To use the select() command, you need to provide a selector that identifies the dropdown menu, and then provide the value or text of the option you want to select.

Here’s an example of how you can use the select() command in Cypress:

javascript
cy.get('select[name="country"]').select('USA');

In this example, the get() command is used to locate a dropdown menu with the name “country” on the page, and then the select() command is used to select the option with the text “USA” from that dropdown.

Cypress Trigger Command

The Cypress trigger() command is used to trigger an event on an element on a web page. This command is particularly useful when you want to simulate a specific event, such as a mouseover or a keypress. To use the trigger() command, you need to provide a selector that identifies the element, and then provide the event you want to trigger.

Here’s an example of how you can use the trigger() command in Cypress:

javascript
cy.get('.element').trigger('mouseover');

In this example, the get() command is used to locate an element with the class “element” on the page, and then the trigger() command is used to simulate a mouseover event on that element.

These are just a few examples of the custom commands that Cypress provides. By leveraging these commands, you can create powerful and expressive tests that accurately simulate user interactions with your web application. Custom commands in Cypress help streamline your test code and make it more readable and maintainable. So go ahead and explore the full range of Cypress custom commands to enhance your testing workflow.

Cypress Custom Commands

image

Custom commands in Cypress allow you to extend the functionality of the Cypress testing framework by creating your own reusable commands. These custom commands can be used to encapsulate complex sequences of actions, assertions, or any other functionality that you find yourself using frequently in your tests. In this section, we will explore different aspects of Cypress custom commands and how they can enhance your testing workflow.

Parent Custom Command in Cypress

A parent custom command in Cypress is a command that encapsulates a sequence of actions or assertions. It serves as a high-level abstraction, allowing you to write more readable and maintainable tests. By creating a parent custom command, you can reduce code duplication and make your tests more modular.

To create a parent custom command, you can use the Cypress.Commands.add() method provided by Cypress. This method takes two arguments: the name of the custom command and a function that defines the behavior of the command. Within the function, you can use existing Cypress commands to perform actions or make assertions.

Here’s an example of a parent custom command that logs in a user:

javascript
Cypress.Commands.add("login", (username, password) => {
cy.visit("/login");
cy.get("#username").type(username);
cy.get("#password").type(password);
cy.get("#login-button").click();
});

With this custom command, you can simply call cy.login(username, password) in your tests to perform the login action. This improves the readability of your tests and makes them easier to maintain.

Child Custom Command in Cypress

A child custom command in Cypress is a command that extends an existing command provided by Cypress. It allows you to add additional functionality or modify the behavior of the existing command. This can be useful when you want to customize the behavior of a command to suit your specific testing needs.

To create a child custom command, you can use the Cypress.Commands.overwrite() method provided by Cypress. This method takes two arguments: the name of the command you want to extend and a function that defines the behavior of the extended command. Within the function, you can call the original command using Cypress.Commands.overwrite().

Here’s an example of a child custom command that extends the cy.click() command to add a delay before clicking:

javascript
Cypress.Commands.overwrite("click", (originalFn, subject, options) => {
const delay = options && options.delay ? options.delay : 500;
cy.wait(delay);
originalFn(subject);
});

With this custom command, you can now pass an additional delay option to the cy.click() command to introduce a delay before the click action is performed. This allows you to simulate scenarios where the user might take some time to interact with the element.

Dual Custom Commands in Cypress

cypress logo

Dual custom commands in Cypress are a combination of parent and child custom commands. They encapsulate a sequence of actions or assertions while also extending an existing command. This provides a powerful way to create reusable and customizable commands.

To create a dual custom command, you can use both the Cypress.Commands.add() and Cypress.Commands.overwrite() methods provided by Cypress. This allows you to define the behavior of the custom command and extend an existing command at the same time.

Here’s an example of a dual custom command that logs in a user and performs a specific action:

javascript
Cypress.Commands.add("loginAndPerformAction", (username, password, action) => {
cy.login(username, password);
cy.get("#action-button").click();
cy.contains(action).click();
});

With this custom command, you can log in a user and perform a specific action in a single command. This improves the readability and reusability of your tests.

Overwriting Existing Cypress Commands

In Cypress, you can also overwrite existing Cypress commands to modify their behavior. This can be useful when you want to customize the behavior of a command to suit your specific testing needs.

To overwrite an existing Cypress command, you can use the Cypress.Commands.overwrite() method provided by Cypress. This method takes two arguments: the name of the command you want to overwrite and a function that defines the behavior of the overwritten command. Within the function, you can call the original command using Cypress.Commands.overwrite().

Importing Cypress Custom Commands

Once you have defined your custom commands, you can import them into your Cypress test files to use them in your tests. Cypress provides a simple way to import custom commands using the support folder.

To import custom commands, create a file named commands.js in the support folder of your Cypress project. In this file, you can import your custom commands using the import statement and register them with Cypress using the Cypress.Commands.add() or Cypress.Commands.overwrite() methods.

Cypress Custom Commands IntelliSense

anysnap 01 oct 2021 at 5 06 15 pm

Cypress provides IntelliSense support for custom commands, making it easier to write tests with custom commands. IntelliSense provides code completion and documentation for custom commands, helping you write tests more efficiently.

To enable IntelliSense for custom commands, you need to install the @types/cypress package in your project. This package provides TypeScript definitions for Cypress, including support for custom commands.

Once you have installed the @types/cypress package, you can start using IntelliSense for custom commands in your Cypress test files. IntelliSense will provide suggestions and documentation for your custom commands as you type, making it easier to write tests.

In conclusion, custom commands in Cypress are a powerful feature that allows you to extend the functionality of the Cypress testing framework. They enable you to create reusable and customizable commands, improving the readability, maintainability, and efficiency of your tests. Whether you need to encapsulate a sequence of actions, extend an existing command, or overwrite an existing command, custom commands provide a flexible and intuitive way to enhance your testing workflow.

Examples and Use Cases

Login Function Example

One of the most common use cases for custom commands in Cypress is implementing a login function. This allows you to easily reuse the login logic across multiple tests, making your test suite more efficient and maintainable.

Let’s say you have a web application with a login page that requires a username and password. Instead of repeating the login steps in every test, you can create a custom command to handle the login process.

Here’s an example of how you can define a custom command for logging in:

javascript
Cypress.Commands.add("login", (username, password) => {
cy.visit("/login");
cy.get("#username").type(username);
cy.get("#password").type(password);
cy.get("#login-button").click();
});

With this custom command, you can now easily log in by simply calling cy.login(username, password) in your tests. This improves the readability of your tests and reduces duplication of code.

Retry Command Example

Another useful example of custom commands in Cypress is implementing a retry mechanism for flaky tests. Flaky tests are tests that occasionally fail due to intermittent issues, such as network delays or race conditions.

Cypress provides a built-in retry command that allows you to retry a specific command or assertion multiple times until it passes or reaches the maximum number of retries.

Here’s an example of how you can define a custom command that retries a specific command:

javascript
Cypress.Commands.add("retryCommand", { prevSubject: true }, (subject) => {
return cy.wrap(subject, { timeout: 5000 }).should("be.visible");
});

In this example, the custom command retryCommand takes a subject as an argument and retries the command should("be.visible") on that subject for a maximum of 5 seconds.

You can then use this custom command in your tests like this:

javascript
cy.get(".element").retryCommand();

This custom command helps to handle flaky tests by automatically retrying the command until it passes or times out. It improves the stability of your tests and reduces false positives.

Promise and Async/Await Example

Cypress also allows you to work with promises and async/await syntax, making it easier to handle asynchronous operations in your tests. You can create custom commands that leverage promises or async/await to perform complex operations or wait for specific conditions.

Here’s an example of how you can define a custom command that waits for an element to be visible using async/await:

javascript
Cypress.Commands.add("waitForElement", { prevSubject: true }, async (subject) => {
await cy.wrap(subject, { timeout: 5000 }).should("be.visible");
});

In this example, the custom command waitForElement takes a subject as an argument and waits for the element to be visible using the should("be.visible") assertion.

You can then use this custom command in your tests like this:

javascript
cy.get(".element").waitForElement();

This custom command simplifies the handling of asynchronous operations in your tests, making them more readable and maintainable.

These examples demonstrate the power and flexibility of custom commands in Cypress. By creating reusable custom commands, you can improve the efficiency, readability, and stability of your test suite.
Conclusion

In conclusion, Cypress commands and Cypress custom commands are powerful tools that can greatly enhance your test automation efforts. The built-in Cypress commands provide a wide range of functionalities to interact with your application, while the custom commands allow you to create reusable and specialized commands tailored to your specific needs. By leveraging these commands, you can write clean, concise, and maintainable tests that are easy to understand and update. Whether you are a beginner or an experienced tester, incorporating Cypress commands and custom commands into your testing workflow will undoubtedly streamline your testing process and help you deliver high-quality software. So, why wait? Start exploring the world of Cypress commands and custom commands today and take your test automation to the next level!

Frequently Asked Questions

How do I install Cypress?

To install Cypress, you can follow these steps:

  1. Open your terminal or command prompt.
  2. Navigate to your project directory.
  3. Run the command npm install cypress to install Cypress locally.

How can I update Cypress to the latest version?

To update Cypress to the latest version, you can use the following command:

npm update cypress

This will update Cypress to the latest available version.

How can I use custom commands in Cypress?

To use custom commands in Cypress, you need to define them in your project‘s support file. Here’s how you can do it:

  1. Create a new file called commands.js in the cypress/support directory.
  2. Define your custom commands using the Cypress.Commands.add() method.
  3. Save the file and restart your Cypress test runner.

Now you can use your custom commands throughout your Cypress tests.

Why are my custom commands not working in Cypress?

If your custom commands are not working in Cypress, make sure to check the following:

  1. Ensure that you have defined your custom commands correctly in the support file.
  2. Verify that the support file is correctly included in your Cypress configuration.
  3. Check for any syntax errors or typos in your custom command definitions.

How can I retry a custom command in Cypress?

To retry a custom command in Cypress, you can use the .retry() method. Here’s an example:

javascript
cy.customCommand().retry(3);

This will retry the custom command up to 3 times if it fails.

How can I use custom assertions in Cypress?

To use custom assertions in Cypress, you can define them using the chai assertion library. Here’s an example:

javascript
chai.Assertion.addMethod('customAssertion', function(expected) {
// Assertion logic goes here
});

Once defined, you can use your custom assertions in your Cypress tests.

How can I use custom selectors in Cypress?

To use custom selectors in Cypress, you can define them using the cy.get() method. Here’s an example:

javascript
Cypress.Commands.add('customSelector', (selector) => {
return cy.get(`[data-custom="${selector}"]`);
});

Once defined, you can use your custom selectors in your Cypress tests.

How can I debug my Cypress tests?

To debug your Cypress tests, you can use the cy.debug() command. Here’s an example:

javascript
cy.customCommand().debug();

This will pause the test execution and open the Cypress test runner’s debug console.

How can I improve the performance of my Cypress tests?

To improve the performance of your Cypress tests, you can follow these best practices:

  1. Use cy.wait() judiciously to avoid unnecessary delays.
  2. Minimize the use of cy.get() and use custom selectors whenever possible.
  3. Use the cy.intercept() command to stub or mock network requests.
  4. Run tests in headless mode (--headless) for faster execution.

Where can I find documentation for Cypress?

You can find the official documentation for Cypress at https://docs.cypress.io. The documentation provides detailed information on how to use Cypress, including guides, API references, and examples.

Scroll to Top