【问题标题】:How to check if element exists using Cypress.io如何使用 Cypress.io 检查元素是否存在
【发布时间】:2019-10-02 09:30:30
【问题描述】:

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

我尝试了以下类似的方法,但没有成功:

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')
            // ...
            // ...
          }
        });
    }
  });
  });

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

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

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

请多多指教。谢谢

【问题讨论】:

标签: javascript selenium-webdriver cypress


【解决方案1】:

之前有人质疑过:Conditional statement in 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})
        }
    })

【讨论】:

    【解决方案2】:

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

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

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

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

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

    阅读更多Cypress documentation on conditional testing

    【讨论】:

    • 感谢@DurkoMatko 这应该是正确的答案。
    • 谢谢,伙计!这是一个可行的解决方案。这应该是公认的答案。
    • 文档说cy.find('.progress') // Errors, cannot be chained off 'cy'。你的意思是if (cy.get("button[data-cy=appDrawerOpener]")...? (不会改变答案是正确的)。
    • if 语句 .length 不再起作用
    【解决方案3】:

    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...
        })
    

    【讨论】:

      【解决方案4】:

      使用 async/await 可以提供简洁的语法:

      const $el = await cy.find("selector")
      if ($el.length > 0) {
        ...
      

      更多信息在这里:https://medium.com/@NicholasBoll/cypress-io-using-async-and-await-4034e9bab207

      【讨论】:

        【解决方案5】:

        我找到了解决办法,希望对你有帮助!

        你可以用这个:

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

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

        Cypress.Commands.add('isElementExist', (element) => {
        
            cy.window().then((win) => {
                const identifiedElement = win.document.querySelector(element)
                cy.log('Object value = ' + identifiedElement)
            });
        })
        

        【讨论】:

          猜你喜欢
          • 2011-03-22
          • 1970-01-01
          • 2021-07-13
          • 2011-07-14
          • 1970-01-01
          • 1970-01-01
          • 2012-12-05
          • 1970-01-01
          • 2012-11-20
          相关资源
          最近更新 更多