Search code examples
javascriptcypress

cypress: error during conditional testing


I'm trying conditional testing in Cypress

cy.get("body").then(($body) => {
    if ($body.find("element1").length > 0,  {timeout: 10000}) {
        cy.get("element1").should("be.visible")
    } else {         
        cy.get("element2").should('be.visible').within(() => {
            //do this and that
        })
    }
});

The problem here is that in case it doesn't find element1, test won't move forward. I tried different approaches but none worked. Either 1st part or 2nd part works but never both. What might be wrong?


Solution

  • The code is essentially correct, except that there is no timeout for that expression.

    cy.get("body").then(($body) => {
      if ($body.find("element1").length > 0) {
        cy.get("element1").should("be.visible")
      } else {         
        cy.get("element2").should('be.visible').within(() => {
    
        })
      }
    })
    

    $body.find("element1") is a jQuery expression not a Cypress command, so you cannot use a timeout option with it.