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

Ayyaz Zafar picture Ayyaz Zafar · Aug 31, 2019 · Viewed 10.9k times · Source

I want to know if an element is visible or not. I am not sure how to do that. I know that we can run this:

cy.get('selector').should('be.visible')

But if element is invisible then test is failed. So I just want a boolean value if element is not visible so I can decide through if condition.

Use case:

I want to open a side menu by clicking on the button only if sidebar is invisible.

if(sidebarIsInvisible){
   cy.get('#sideMenuToggleButton').click();
}

Is this possible?

I really appreciate for any contribution.

Thanks in advance

Answer

DurkoMatko picture DurkoMatko · Aug 31, 2019

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');
    }
});