Javascript 如何在Cypress中检查DOM中是否存在元素?
我想知道如何在Cypress中检查网页的DOM中是否存在元素 Selenium中这段代码的等价物在Cypress中是什么:Javascript 如何在Cypress中检查DOM中是否存在元素?,javascript,selenium,cypress,Javascript,Selenium,Cypress,我想知道如何在Cypress中检查网页的DOM中是否存在元素 Selenium中这段代码的等价物在Cypress中是什么: Boolean Display = driver.findElement(By.xpath("locator")).isDisplayed(); 1.要检查DOM中是否存在元素,请执行以下操作: cy.get(selector).should('exist') 2.要检查DOM中是否不存在该元素,请执行以下操作: cy.get(selector).s
Boolean Display = driver.findElement(By.xpath("locator")).isDisplayed();
1.要检查DOM中是否存在元素,请执行以下操作:
cy.get(selector).should('exist')
2.要检查DOM中是否不存在该元素,请执行以下操作:
cy.get(selector).should('not.exist')
3.检查元素是否可见:
cy.get(selector).should('be.visible')
4.检查元素是否不可见:
cy.get(selector).should('not.be.visible')
5.使用JQuery:
cy.get('body').then(($body) => {
if ($body.find(selector).length > 0) {
//element exists do something
}
})
要使用xpath定位器进行查询,请安装扩展 使用npm安装 npm安装-D cypress xpath 用纱线安装 添加CypressXPath-dev 在测试中 cy.xpathlocator//driver.findElementBy.xpathlocator 还要添加可见性检查 cy.xpathlocator//driver.findElementBy.xpathlocator .should'be.visible'//显示 或 cy.xpathlocator//driver.findElementBy.xpathlocator .should'not.be.hidden'//显示
我可以这样做吗?:var exists=cy.xpathlocator.should'be.visible'//true或false如果您的xpath定位器合并了该方法,您可以像这样测试值cy.xpathlocator-with-count.thencount=>{const exists=!!count;…谢谢,这回答了我的问题,我不明白为什么没有解决方案可以像在Selenium中那样以更简单的方式实现这一点。在Cypress中,您不应该从命令链中提取值,因为它可以打破Selenium没有的重试机制。