skip to Main Content

I am trying to pass an assertion to if condition and execute a logic when the condition is met and another logic when condition is failed.

Since the test is failing on failure of assertion i am not able to achieve the desired result.

I tried the following…

if(cy.get("div").length>0)

{

cy.log("print this")

}

else

{

cy.log("print this")

}

or

if(cy.get("div").should('have.length.greaterThan',0)

{

cy.log("print this")

}

else

{

cy.log("print this")

}

2

Answers


  1. So, certain Cypress commands (inlcudes cy.get() contain implicit assertions – meaning that Cypress will fail a test if the implicit assertion is not met. In this case, if cy.get() fails to find an element, that fails the implicit assertion, and the test will fail.

    Additionally, Cypress commands will yield objects that are of type Chainable<T>, meaning they don’t yield traditional objects that can have .length appended to them.

    Instead of using cy.get('div'), we get the parent element and search for the div element using JQuery functions.

    cy.get('body') // get the parent of the div
      .then(($body) => { // then unwraps the Chainable<JQueryHTMLElement> Object
        if ($body.find('div').length) { // We can use JQuery commands directly on the yielded $body element
          // code if `div` has a length greater than 0
        } else {
          // code if `div` has a length of 0
        }
      });
    
    Login or Signup to reply.
  2. To pass the assertion to if() change cy.get() to Cypress.$().

    if(Cypress.$('div').length > 0) {
      cy.log("print this")
    } else {
      cy.log("print that")
    }
    

    cy.get() is a wrapper around Cypress.$() that retries until timeout then fails.

    Cypress.$() just returns a jQuery object which has length === 0 if it fails, but in either case the test continues.

    Make sure the page has finish loading (no fetch not yet responded) before running any if() condition.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search