Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 323
Ayyaz Zafar Avatar asked Aug 31 '19 11:08

Ayyaz Zafar


People also ask

How do you know if an element is visible or not in Cypress?

Check if Element is visible If the popup element object is returned, then the code proceeds to click on the popup. However if null, the code exits at the return code block. All this is made possible through Cypress conditional testing feature.

How does Cypress handle elements not visible?

Execution Results Cypress has another technique for handling hidden elements. For example, to click a hidden element we can use the Cypress command click and pass the option {force : true} as a parameter to it - click({ force: true }). This modifies the hidden characteristics of the hidden element and we can click it.


1 Answers

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');
    }
});
like image 74
DurkoMatko Avatar answered Sep 20 '22 12:09

DurkoMatko