Home > Mobile >  How I can make my if conditions work in cypress?
How I can make my if conditions work in cypress?

Time:04-12

I want to check an element's visibility. In this code, cypress tries to find cy.get('[data-cy="repetitions-count-box"]') and fails if it not exist. It should go in else part, but doesn't. Any suggestions? cypress fail message

cy.get('[data-cy="repetitions-count-box"]').then(($rptBox) =>{
                if($rptBox.is(':visible')){
                        const repeat = $rptBox.text()
                        Cypress.env('repeatNumber', repeat)
                        cy.log(repeat)
                   
                }else{
                    cy.log('There is no repetition.')
                }
            })

CodePudding user response:

It happens because you locate that "dynamic" selector, repetitions-count-box outside the conditions. You have to find it in a static parent element which will always be rendered, e.g. .app:

    cy.get('.app').then($app => {
        if ($app.find('[data-cy="repetitions-count-box"]').is(':visible')) {

        // ...

        } else {

       // ...
        
        }
    });

CodePudding user response:

You can use the jquery length to check the presence of the element in the dom and apply the if-else condition. If length is greater than 0 that means the element exists in the DOM.

cy.get('body').then(($body) => {
  if ($body.find('[data-cy="repetitions-count-box"]').length > 0) {
    //Element exists
    const repeat = $rptBox.text()
    Cypress.env('repeatNumber', repeat)
    cy.log(repeat)
  } else {
    //Element doesn't exist
    cy.log('There is no repetition.')
  }
})
  • Related