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

328
Views
Cypress - If Else based on Presence of element without throwing 'Expected to find element: but never found it.'

While using Cypress - I would like to understand ways to do action vs not do action based on element found or not. I tried all below with help from Google search - but ended up with just a bunch of hours wasted:

  1. cy.xpath('').then($ele => {}) - throws Timed out retrying after 20000ms: Expected to find element: //div[text()='hello']//div, but never found it.
  2. cy.xpath('').then(ele => { eleLenght = Cypress.$(ele).length}) - throws Timed out retrying after 20000ms: Expected to find element: //div[text()='hello']//div, but never found it.
  3. cy.xpath('').then($ele => {}).catch({}) - catch is not defined
  4. cy.xpath('').its('lenght').then($ele => {}) - throws Timed out retrying after 20000ms: Expected to find element: //div[text()='hello']//div, but never found it.
  5. cy.xpath('').should('be:visisble').then($ele => {}) - throws Timed out retrying after 20000ms: Expected to find element: //div[text()='hello']//div, but never found it.

My case: If an element is present - I want to try to delete it, but if not present - gracefully continue without throwing the annoying error as above!

Can someone please help here? Conditional testing doc provided in cypress does'nt help at all!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can easily do it with jquery notation:

if (Cypress.$("#your-element-id").length > 0) {
    //do something
} else {
    //do nothing
}

Have you tried below?

cy.xpath('').should('have.length.gt',0).then($ele => {console.log($ele)})
about 4 years ago · Juan Pablo Isaza 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!