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()
}
})
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" )