Cypress : XPATH - Do something if the element exists

Viewed 99

I need to click on a button if the button exists. I am using the cypress xpath. Currently i am using below code but not working

cy.xpath('//button[text()="New"]')
  .then(($button) => {
    if ($button.is(':visible')) {
      cy.log('visible')
      cy.xpath('//button[text()="New"]').click();
    } else {
      //do something
    }
  })
2 Answers

In case if you want to click a button based on it existence, you can do like this:

cy.get('body').then(($body) => {
  if ($body.find('button:contains("New")').length > 0) {
    cy.log('visible')
    cy.xpath('//button[text()="New"]').click()
  } else {
    //do something
  }
})

In case if you want to check if the element is visible and then click on it.

cy.xpath('//button[text()="New"]').then(($button) => {
  if ($button.is(':visible')) {
    cy.log('visible')
    cy.wrap($button).click()
  } else {
    //do something
  }
})

XPath has a count() function that tells you if the element exists.

cy.xpath('count(//button[text()="New"])').then(count => {  // check existence first
  if (count) {
    cy.xpath('//button[text()="New"]').then($button => 
      if ($button.is(':visible')) {
        cy.log('visible')
        cy.wrap($button).click()
      } else {
        //do something
      }
  }
})

Splitting exists and visible checks like that will work if the DOM is stable.

Related