Search code examples
cypresscypress-conditional-testing

How to know if element is visible or not in a Cypress test


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 the element is invisible then the 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?


Solution

  • 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
      }
    })
    

    You need to differentiate between button existing and button being visible. The code below differentiates between three 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');
        }
    });