Ancora Imparo - I'm still learning (Michelangelo at 87)

How to check if an element exists or not using Cypress.io

Element presence is one of the first things you should test with Cypress in your project. In this article, we will look at how to test if an element exists or not. Also, if it exists, how do you check whether it is visible or not.

Check if Element exists

If you wish to check if an element exists without failing, you need to use conditional testing. Let’s take an example of a web page that has both a Banner and a Popup element with class ‘banner’ and ‘pop’. We can check if these elements exist on the webpage in the following way:

cy.get('body')
  .then($body => {
    if ($body.find('.banner').length) {
      return '.banner';
    }
    return '.popup';
  })
  .then(selector => {
    cy.get(selector);
  });

After running this code, you will get the body element returned. Subsequently, you can query the element within the body using the “find” method, the element’s ID or class and a callback function. If the element exists, the callback function will return true. If the element does not exist, the callback function will return false.

Check if Element is visible

Let us reconsider our example of the webpage with a banner and a popup. As the popup would not be visible initially, to test for its visibility at any time, we can write the following code:

cy.get('popup')
    .then($popup => {
        if ($popup.is(':visible')) {
            cy.get('popup').click()
        } 
        else{
            return
        }
    })

The code above checks if the popup element is visible. The callback function then gets a return value $popup which either returns null or the popup element object. If the popup element object is returned, then the code proceeds to click on the popup. However if null, the code exits at the return code block. All this is made possible through Cypress conditional testing feature.

About the Autor

Jamiu Idowu

Jamiu Idowu

Entrepreneur seeking to shape the world through IT and emerging technologies. Enjoys research and technical writing, and can serve as a bridge between technology and its users.

Liked this article?

We have a lot more where that came from!
Join the subscribers who stay ahead of the pack.

By entering your email, you agree to our Terms of Service and Privacy Policy.