how to assert if else in conditional testing?

Viewed 116

Hi have this code and i want to assert the $element if visible or not visible. How can i do it? i tried should and expect but its failing

 cy.get('.cloudfront_new_header').then(($element) => {
   if ($element.style.visibility = "hidden"){
     cy.log('Visible')
   } else { 
     cy.log('NotVisible')
   }
 })
2 Answers

You have to use the Jquery method is(':visible') for this.

cy.get('.cloudfront_new_header').then(($ele) => {
  if ($ele.is(':visible')) {
    cy.log('Visible')
  } else {
    cy.log('NotVisible')
  }
})

You are almost there, the $element variable is a jQuery wrapper object but you want to check the style property of the element itself, so extract the native element via $element[0].

cy.get('.cloudfront_new_header').then(($element) => {
  if ($element[0].style.visibility = "hidden") {
    cy.log('Visible')
  } else { 
    cy.log('NotVisible')
  }
})

From jQuery :visible selector

Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.

Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.

Bottom line, it depends on the definition of visibility. There's a whole discussion in the Cypress notes, but this applies when using .should('be.visible).

To perform an if() you need to conform to the jQuery definition, or directly test the style as above.

Related