How to check if element exists in DOM in Cypress?

Viewed 7473

I want to know how to check if an element exists in the DOM of a web page in Cypress.

What would the equivalent of this piece of code in Selenium be in Cypress:

Boolean Display = driver.findElement(By.xpath("locator")).isDisplayed();
2 Answers

1.To check element exists in the DOM:

cy.get(selector).should('exist')

2.To check that the element doesn't exist in DOM:

cy.get(selector).should('not.exist')

3.To check that element is visible:

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

4.To check that element is not visible:

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

5.Using JQuery:

cy.get('body').then(($body) => {
    if ($body.find(selector).length > 0) {
        //element exists do something
    }
})

To query with an xpath locator, install the cypress-xpath extension.

Install with npm
npm install -D cypress-xpath

Install with Yarn
yarn add cypress-xpath --dev

In the test

cy.xpath(locator)            // driver.findElement(By.xpath("locator"))

Add a visibility check as well,

cy.xpath(locator)            // driver.findElement(By.xpath("locator"))
  .should('be.visible')      // isDisplayed()

or

cy.xpath(locator)            // driver.findElement(By.xpath("locator"))
  .should('not.be.hidden')   // isDisplayed()
Related