How I can Execute next command if current command element is not found in cypress?

281 Views Asked by At

Here is below code I want to search "select-dropdown" if its visible than execute if block , if not found than instead of returning error that "select-dropdown" not found, it should execute else block and should click on button.

but it still return error that "select-dropdown" never found instead of clicking on button in else block . how I can acheive my desire behavior to check if "select-dropdown" found then execute if block code, otherwise execute else block code instead of returning not found error.

I tried try catch but facing same issue.

  cy.get("body").then($body=>{
   if($body.has("select-dropdown")){
    cy.get("select-dropdown).trigger("mousehover")
    }
   else{
      cy.get("#Btn2").click()
       }
  })
3

There are 3 best solutions below

0
On BEST ANSWER

JQuery's .has() function does not return true or false, but rather a new JQuery object. I believe that even if an element is not found, because that object with a length of 0 is returned, your if/else always evaluates to true, as the object is considered Truthy. Instead, you can check for the length of that object to determine if it was successfully found. (If an object is not found, then the length will be 0, which is a Falsy value.)

cy.get("body").then(($body) => {
    if($body.has("select-dropdown").length) {
        cy.get("select-dropdown").trigger("mousehover")
    } else{
        cy.get("#Btn2").click()
    }
})

It is a little obscured in the JQuery example docs, but they use the same strategy. (Note: slightly different formatting from JQuery)

( $( "ul" ).has( "li" ).length ? "Yes" : "No" )
2
On

I don't know if it fully covers your question, but have you tried the 'end' command? https://docs.cypress.io/api/commands/end#Syntax

I'm still new to Cypress (as well?), so there might be better ways (or more correct ways).

Would assume it is placed after: cy.get("select-dropdown).trigger("mousehover")

0
On

You make things much harder than necessary for yourself. Just use the Cypress built-in jquery like this:

const itExists = Cypress.$("select-dropdown").length

if (itExists) {
  cy.get("select-dropdown").trigger("mousehover")
} else {
  cy.get("#Btn2").click()
}

Be careful about the loading of the page. The reason you want if-else means that element is sometimes present, but sometimes not. But any code that does needs it should check for a period of time, and that is exactly not happening.