如何使用 Cypress.io 检查元素是否存在 [英] How to check if element exists using Cypress.io

查看:43
本文介绍了如何使用 Cypress.io 检查元素是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to check if element is present or not, so that certain steps can be performed if element is present. Else certain different steps can be performed if element is not present.

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

I tried something like below but it didn't work:

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() 承诺的部分

I am looking for a simple solution, which can be incorporated with simple javascript if else block or then() section of the promise

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

Something similar to Webdriver protocol's below implementions:

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

请多多指教.谢谢

推荐答案

cypress 所有步骤都是异步的,所以你应该在命令文件或页面目标文件中制作通用功能,..

cypress all steps are async ,, so that you should make common function in commands file or page object file,,..

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

这篇关于如何使用 Cypress.io 检查元素是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆