如何检查 Cypress 的 DOM 中是否存在元素?

Ami*_*ine 7 javascript selenium cypress

我想知道如何检查 Cypress 网页的 DOM 中是否存在某个元素。

Selenium 中的这段代码在 Cypress 中相当于什么:

Boolean Display = driver.findElement(By.xpath("locator")).isDisplayed();
Run Code Online (Sandbox Code Playgroud)

Ala*_*Das 10

1.检查DOM中是否存在元素:

cy.get(selector).should('exist')
Run Code Online (Sandbox Code Playgroud)

2.检查DOM中是否不存在该元素:

cy.get(selector).should('not.exist')
Run Code Online (Sandbox Code Playgroud)

3.检查该元素是否可见:

cy.get(selector).should('be.visible')
Run Code Online (Sandbox Code Playgroud)

4.检查该元素不可见:

cy.get(selector).should('not.be.visible')
Run Code Online (Sandbox Code Playgroud)

5.使用JQuery:

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


小智 3

要使用 xpath 定位器进行查询,请安装cypress-xpath扩展。

使用 npm 安装
npm install -D cypress-xpath

使用纱线安装
yarn add cypress-xpath --dev

在测试中

cy.xpath(locator)            // driver.findElement(By.xpath("locator"))
Run Code Online (Sandbox Code Playgroud)

还添加可见性检查,

cy.xpath(locator)            // driver.findElement(By.xpath("locator"))
  .should('be.visible')      // isDisplayed()
Run Code Online (Sandbox Code Playgroud)

或者

cy.xpath(locator)            // driver.findElement(By.xpath("locator"))
  .should('not.be.hidden')   // isDisplayed()
Run Code Online (Sandbox Code Playgroud)