Cypress: How to know if element is visible or not in using If condition?

Cypress allows jQuery to work with DOM elements so this will work for you:

cy.get("selector_for_your_button").then($button => {
  if ($button.is(':visible')){
    //you get here only if button is visible
  }
})

UPDATE: You need to differentiate between button existing and button being visible. The code below differentiates between 3 various scenarios (exists & visible, exists & not visible, not exists). If you want to pass the test if the button doesn’t exist, you can just do assert.isOk('everything','everything is OK')

cy.get("body").then($body => {
    if ($body.find("selector_for_your_button").length > 0) {   
    //evaluates as true if button exists at all
        cy.get("selector_for_your_button']").then($header => {
          if ($header.is(':visible')){
            //you get here only if button EXISTS and is VISIBLE
          } else {
            //you get here only if button EXISTS but is INVISIBLE
          }
        });
    } else {
       //you get here if the button DOESN'T EXIST
       assert.isOk('everything','everything is OK');
    }
});

Leave a Comment