cypresscypress-conditional-testing

if-else containing a cy.get as an condition


I am trying to create an if-else condition that includes cy.get()

if (!cy.get('.modal.modal--active')) {
    cy.reload()
} else {
    // some codes here
}

Upon testing the code the .modal.modal--active element is not present, instead of executing the cy.reload() line, it returns an error.

Expected to find element: .modal.modal--active, but never found it.

Is it possible to have the if block running and not return AssertionError?


Solution

  • Cypress commands should be chained, not used as expressions in if() statements.

    cy.get(something) fails the test when something isn't found.

    Adding a negative assertion like cy.get(something).should('not.exist') does the opposite, it passes when something isn't found.

    The third way (undocumented) is .should(() => undefined), something like this

    cy.get('.modal.modal--active')
      .should(() => undefined)          
      .then(activeModal => {
        const found  = activeModal.length  
        if (!found) {
          cy.reload()
        } else {
          ...   
        }
      })
    

    The documented way is using jQuery .find() as follows:

    cy.get('body').then((body) => {  // always succeeds
        const modalActive = body.find('.modal.modal--active')
        const found  = activeModal.length
        if (!found) {
          cy.reload()
        } else {
          ...   
        }
    })
    

    Generally if/else is not supported in Cypress testing because best practice is to set the test page so that if/else conditions are not necessary.