最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if element exists in DOM in Cypress? - Stack Overflow

programmeradmin0浏览0评论

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

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();
Share Improve this question edited Jul 30, 2024 at 5:34 Sebold 1587 bronze badges asked Mar 28, 2021 at 10:52 AmineAmine 9413 gold badges16 silver badges38 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 9

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

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
    }
})
发布评论

评论列表(0)

  1. 暂无评论