How to Check if Element Exists Without Failing in Cypress

How to Check if Element Exists Without Failing in Cypress

Ferenc Almasi β€’ 2021 October 01 β€’ Read time 2 min read
  • twitter
  • facebook

If you want to verify if an element exists without failing (you might don't know if the element will exist or not), then you need to do conditional testing, which you can do in the following way:

Copied to clipboard! Playground
cy.get('body')
  .then($body => {
    if ($body.find('.banner').length) {
      return '.banner';
    }

    return '.popup';
  })
  .then(selector => {
    cy.get(selector);
  });

You can get the body β€” which will be always present β€” and query the element inside a then callback, then return the right selector, or either true or false that you can use later. But the question is, should you do conditional testing? The short answer is no, and here's why:


The problem with conditional testing

Introducing conditions into your test cases can often lead to random failures, as your tests are not deterministic anymore. If you don't know the exact state of your application upfront, there will be a chance of running into a random failure. Luckily, what you might be trying to do, could be achieved in different ways.

One possible solution is using a callback as mentioned before. Another way is to be explicit about setting up the right conditions for your app. This includes things like:

  • Setting the right query parameters in the URL
  • Setting the right cookies or items in local storage
  • Setting the right headers for a request
Copied to clipboard!
cy.visit('https://webtips.dev?popup=true');

You can also use try-catch for error handling. However, no matter which approach you take, if you need conditions in the first place, you cannot be sure that your tests will be 100% deterministic.

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to check if element exists without failing in Cypress
If you would like to see more webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.