如何使用 Cypress.io 检查元素是否存在

use*_*016 39 javascript selenium-webdriver cypress

如何检查元素是否存在,以便在元素存在的情况下可以执行某些步骤。否则,如果元素不存在,则可以执行某些不同的步骤。

我尝试了类似下面的方法,但没有奏效:

Cypress.Commands.add('deleteSometheingFunction', () => {
  cy.get('body').then($body => {
    if ($body.find(selectors.ruleCard).length) {
      let count = 0;
      cy.get(selectors.ruleCard)
        .each(() => count++)
        .then(() => {
          while (count-- > 0) {
            cy.get('body')
            // ...
            // ...
          }
        });
    }
  });
  });
Run Code Online (Sandbox Code Playgroud)

我正在寻找一个简单的解决方案,它可以与简单的 javascript if else block 或then()部分合并

类似于 Webdriver 协议的以下实现:

  1. driver.findElements(By.yourLocator).size() > 0
  2. 检查等待中元素的存在

好心提醒。谢谢

Dur*_*tko 59

我只想补充一点,如果您决定通过检查command的.length属性来执行 if 条件cy.find,则需要尊重 cypress 的异步性质。

示例: 尽管 appDrawerOpener 按钮存在,但以下条件评估为 false

    if (cy.find("button[data-cy=appDrawerOpener]").length > 0)    //evaluates as false
Run Code Online (Sandbox Code Playgroud)

但是这个评估为真,因为$body变量已经解决了,因为你是.then()承诺的一部分:

    cy.get("body").then($body => {
        if ($body.find("button[data-cy=appDrawerOpener]").length > 0) {   
            //evaluates as true
        }
    });
Run Code Online (Sandbox Code Playgroud)

Cypress 文档中阅读有关条件测试的更多信息

  • if 语句 .length 不再起作用 (13认同)
  • 谢谢@DurkoMatko 这应该是正确的答案。 (6认同)
  • 文档说 `cy.find('.progress') // 错误,无法链接到 'cy'`。您的意思是“if (cy.get("button[data-cy=appDrawerOpener]")...`?(不会改变答案是正确的)。 (5认同)
  • @AshokkumarGanesan 它对我来说也不起作用。您找到其他解决方案了吗? (3认同)
  • 我不明白您的解决方案与问题中的解决方案有何不同。在问题中,作者也使用了 ```cy.get('body').then( <find with $body tag>)``` 你也做了同样的事情。您能解释一下为什么您的解决方案是正确的吗? (3认同)
  • @AshokkumarGanesan 为我工作了很长时间:)这仍然是一个很好的解决方案 (2认同)

Mr.*_* J. 11

之前有人质疑过:cypress中的条件语句

因此你基本上可以试试这个:

cy.get('header').then(($a) => { 
        if ($a.text().includes('Account')) {
            cy.contains('Account')
            .click({force:true})
        } else if ($a.text().includes('Sign')) { 
            cy.contains('Sign In')
            .click({force:true})  
        } else {
            cy.get('.navUser-item--account .navUser-action').click({force:true})
        }
    })
Run Code Online (Sandbox Code Playgroud)


Ric*_*ade 7

我找到了解决方案,希望有帮助!

你可以使用这个:

cy.window().then((win) => {
        const identifiedElement = win.document.querySelector(element)
        cy.log('Object value = ' + identifiedElement)
    });
Run Code Online (Sandbox Code Playgroud)

您可以将其添加到 Cypress 中的commands.js 文件中

Cypress.Commands.add('isElementExist', (element) => {

    cy.window().then((win) => {
        const identifiedElement = win.document.querySelector(element)
        cy.log('Object value = ' + identifiedElement)
    });
})
Run Code Online (Sandbox Code Playgroud)


Man*_*tel 5

cypress 的所有步骤都是异步的,因此您应该在命令文件或页面对象文件中创建通用功能,..

    export function checkIfEleExists(ele){
    return new Promise((resolve,reject)=>{
        /// here if  ele exists or not
        cy.get('body').find( ele ).its('length').then(res=>{
            if(res > 0){
                //// do task that you want to perform
                cy.get(ele).select('100').wait(2000);
                resolve();
            }else{
                reject();
            }
        });
    })
}


// here check if select[aria-label="rows per page"] exists
cy.checkIfEleExists('select[aria-label="rows per page"]')
.then(e=>{
        //// now do what if that element is in ,,..
        })
.catch(e=>{
    ////// if not exists...
    })
Run Code Online (Sandbox Code Playgroud)