javascriptselenium-webdriverxpathcypress

How to check if element exists in DOM in Cypress?


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();

Solution

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