How to check if element exists using Cypress.io – Cypress

Photo of author
Written By M Ibrahim
cypress selenium-webdriver

Quick Fix: To check if an element exists using Cypress.io, create a Promise-based function, such as checkIfEleExists, in the command or page object file. This function finds the element, counts its occurrences, and performs specific actions based on the existence of the element, resolving or rejecting the Promise accordingly.

The Problem:

Design an efficient solution to verify the presence of a particular element and execute different steps based on its existence. The solution should be compatible with both if-else blocks and promises using the then() method.

The Solutions:

Solution 1: Using a custom command to check if an element exists

In Cypress, it is important to remember that all steps are asynchronous. Hence, creating a common function called checkIfEleExists either in the commands.js file or in a page object file is advisable.

Here’s how the checkIfEleExists function would look like in the commands.js file:

export function checkIfEleExists(ele){
        return new Promise((resolve, reject) => {
            /// check if the element exists or not
            cy.get('body').find(ele).its('length').then(res => {
                if (res > 0) {
                    //// perform your desired actions here
                    cy.get(ele).select('100').wait(2000);
                    resolve();
                } else {
                    reject();
                }
            });
        })
    }

In your test file, you can then use this function as follows:

cy.checkIfEleExists('select[aria-label="rows per page"]')
    .then(e => {
            //// now perform the actions if the element exists
            })
    .catch(e => {
        ////// perform actions if the element does not exist
        })

This approach ensures that your code remains DRY (Don’t Repeat Yourself) and improves readability.

Solution 2: Use get() and its aliases

You can utilize the `cy.get()` command and its aliases, such as `.should()`, `.its()`, and `.then()`, to check for the presence of an element effectively.

Here’s an example:

cy.get(selectors.ruleCard).should('exist');

This will check if the element with the selector selectors.ruleCard exists in the DOM and assert that it should exist. If the element doesn’t exist, the test will fail.

If you want to perform different actions based on whether the element exists or not, you can use the .then() method. For instance:

cy.get(selectors.ruleCard).then((ruleCard) => {
  if (ruleCard.length) {
    // Do something if the element exists
  } else {
    // Do something else if the element does not exist
  }
});

Or, you can use the .its() alias to check a specific property of the element, like its length:

cy.get(selectors.ruleCard).its('length').then((length) => {
  if (length > 0) {
    // Do something if the element exists
  } else {
    // Do something else if the element does not exist
  }
});

These methods give you more control and flexibility in checking for the existence of an element and taking appropriate actions accordingly.

Solution 3: Using jQuery’s .length property

This solution utilizes jQuery’s `.length` property to check if an element is present on the page. Here’s an improved and detailed explanation of the code:

cy.get('body').then(($body) => {
  // Check if the element with the selector 'selectors.ruleCard' exists in the DOM
  if ($body.find(selectors.ruleCard).length) {
    // Element is present, perform certain actions
    // ...
    // ...
  } else {
    // Element is not present, perform different actions
    // ...
    // ...
  }
});
  1. cy.get('body'): This command retrieves the <body> element of the web page.

  2. .then(($body) => {}): The .then() method is used to handle the asynchronous nature of Cypress commands. It takes a callback function as an argument, which is executed when the element is found. The $body parameter represents the <body> element.

  3. $body.find(selectors.ruleCard).length: This jQuery expression checks for the presence of the element with the selector selectors.ruleCard within the <body> element. It returns the number of matching elements found.

  4. if ($body.find(selectors.ruleCard).length): This conditional statement checks if the length of the matched elements is greater than 0. If it is, it means the element is present on the page.

  5. Inside the if block, you can perform the necessary actions that should be executed when the element is found.

  6. If the element is not found, the else block will be executed, and you can perform the alternative actions.

Solution 4: Using “Cypress.Commands.add()” to Create a Custom Command for Element Checking

The solution involves creating a custom command using Cypress.Commands.add() to check if an element exists on the web page. Here’s a step-by-step explanation:

  1. Create a Custom Command:

    • In your commands.js file, add the following code:

      Cypress.Commands.add('isElementExist', (element) => {
        cy.window().then((win) => {
          const identifiedElement = win.document.querySelector(element);
          cy.log('Object value = ' + identifiedElement);
        });
      });
      
  2. Usage:

    • You can now use the isElementExist() command within your test scripts to check for the presence of an element. Here’s an example:

      cy.visit('https://example.com');
      cy.isElementExist('#element-id'); // Check if an element with the ID "element-id" exists
      
    • The isElementExist() command will log the value of the identified element to the Cypress Test Runner console. If the element exists, the log will show the element’s HTML code. If the element doesn’t exist, the log will show "null".

  3. Conditional Execution:

    • Based on the presence or absence of the element, you can perform different actions in your test. For example:

      cy.isElementExist('#element-id').then((element) => {
        if (element) {
          // Element exists - Perform certain actions
        } else {
          // Element doesn't exist - Perform different actions
        }
      });
      
  4. Advantages:

    • The custom command isElementExist() provides a concise and readable way to check for the existence of elements in your tests.
    • It allows you to perform conditional checks and execute different actions based on the presence or absence of elements.
    • You can easily reuse this custom command in multiple test scripts.

Solution 5: Utilize Cypress’s `.find()` Method for Existence Validation

Cypress provides the `.find()` method specifically for examining the presence or absence of elements on a web page. This approach not only verifies the element’s presence but also ensures that the DOM is stable before proceeding with further actions. Here’s how you can implement it:

1. Locate the Element:
“`
cy.get(‘[data-testid=”element-to-check”]’);
“`

  1. Check for Its Existence:
.then(($element) =&gt; {
  if ($element.length) {
    // Element is present, perform actions specific to its existence
  } else {
    // Element is not present, perform alternative actions
  }
});

By employing `.find()` and the subsequent conditional logic, you can create robust tests that adapt to the presence or absence of specific elements, ensuring reliable test execution and accurate results.