How to Check if Element Exists Without Failing in Cypress
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:
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
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:
Resources:
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: