Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
How to not break Cypress tests if element you'r looking for is not exist

I have the div with classname 'okrSelectorSelect__value-container' in DOM.

<div class="okrSelectorSelect__value-container"><div>

This div is optional. I want to click on it and do some additional tests with block that appears after that IF IT EXIST. I'm trying this.

cy.get('.okrSelectorSelect__value-container').then(($higherObjectivePick) => {
 if ($higherObjectivePick.length > 0) {
  $higherObjectivePick.click();
 }
});

But got this when block is not on the page

enter image description here

Here is my solution, but looks like there is much more beautiful ways to do that.

 cy.get('body').then($body => {
    if ($body.find('.okrSelectorSelect__value-container').length > 0) { 
      cy.get('.okrSelectorSelect__value-container').click();
      cy.get('.okrSelectorSelect__option').eq(higherOrderObjectiveNumber).click();
    }
  }); 
about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You could use jquery operators to check the existence of an element and wrap that function as below, adding to your support.js file:

Cypress.Commands.add("checkIfClassExists", (classToFind) => {
    return Cypress.$(classToFind).length>0
})

Then in your tests:

if (cy.checkIfClassExists('.okrSelectorSelect__value-container')) {
    //do something
} else {
    //do nothing 
}
about 4 years ago · Santiago Trujillo Report

0

I usually do the same like you but it would be more pretty to create a custom command for it like this:

Cypress.Commands.add("clickIfExists",(containerId , ItemId)=>{
  cy.get('body').then($body => {
    if ($body.find(containerId).length > 0) { 
      cy.get(ItemId).click();
    }
  }); 
})

and by this way you can always call it like that if you would like to click on .okrSelectorSelect__option :

cy.clickIfExists(".okrSelectorSelect__value-container",".okrSelectorSelect__option")
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!