Sign Up

Sign In

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

You must login to ask question.

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

if else in Cypress if element is visible or not visible

if else in Cypress if WebElement is visible or not visible

In Cypress, you can use the should() method to check if an element is visible or not and then use JavaScript’s if-else statement to perform different actions based on the visibility of the element.

Here is an example of how to use if-else statement to check if an element is visible or not and perform different actions based on its visibility:

cy.get('.my-element').should('be.visible')
  .then(($el) => {
    // perform some action if the element is visible
    cy.wrap($el).click();
  })
  .catch(() => {
    // perform some action if the element is not visible
    cy.get('.my-element').click();
  });

In this example, the cy.get() method is used to select the element with the class my-element, the should('be.visible') method is used to check if the element is visible. If the element is visible, the then() method is used to perform some action on the element and if the element is not visible, the catch() method is used to perform some other action.

Alternatively, you can use the .should('exist') method instead of .should('be.visible') to check if the element is present in the DOM or not.

cy.get('.my-element').should('exist')
  .then(($el) => {
    if($el.is(':visible')){
        // perform some action if the element is visible
        cy.wrap($el).click();
    } else {
        // perform some action if the element is not visible
        cy.log('element not visible')
    }
  })
  .catch(() => {
    // perform some action if the element is not present in the DOM
    cy.log('element not present in the DOM')
  });

In this example, the if($el.is(':visible')) statement is used to check if the element is visible or not after checking that element exists.

Please note that, it’s important to make sure that the element is loaded and available before checking its visibility or existence.

For more interesting blogs . Click here

Author: Ghulam Nabi

Related Posts

Parallelization in Cypress

Cypress to perform a file upload

Cannot find name 'Cypress'

Draw a line using Cypress

Leave a comment

You must login to add a new comment.