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

查看:1510
本文介绍了如何使用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结合使用 如果不是阻止或承诺的 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所有步骤都是async,因此您应该在命令文件或页面目标文件中使用通用功能,..

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天全站免登陆