赛普拉斯:如果使用IF条件,如何知道元素是否可见? [英] Cypress: How to know if element is visible or not in using If condition?

查看:12
本文介绍了赛普拉斯:如果使用IF条件,如何知道元素是否可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道元素是否可见。我不知道该怎么做。 我知道我们可以运行:

cy.get('selector').should('be.visible')

但如果元素不可见,则测试失败。因此,如果元素不可见,我只需要一个布尔值,这样我就可以通过IF条件来决定。

使用案例:

仅当侧栏不可见时,我才想通过单击按钮打开侧边菜单。

if(sidebarIsInvisible){
   cy.get('#sideMenuToggleButton').click();
}

这可能吗?

非常感谢您的贡献。

提前感谢

推荐答案

Cypress允许jQuery使用DOM元素,因此这将适用于您:

cy.get("selector_for_your_button").then($button => {
  if ($button.is(':visible')){
    //you get here only if button is visible
  }
})

update:您需要区分按钮已存在和按钮是否可见。下面的代码区分了3种不同的场景(存在&;可见、存在&;不可见、不存在)。如果您想在该按钮不存在的情况下通过测试,您只需执行assert.isOk('everything','everything is OK')

cy.get("body").then($body => {
    if ($body.find("selector_for_your_button").length > 0) {   
    //evaluates as true if button exists at all
        cy.get("selector_for_your_button']").then($header => {
          if ($header.is(':visible')){
            //you get here only if button EXISTS and is VISIBLE
          } else {
            //you get here only if button EXISTS but is INVISIBLE
          }
        });
    } else {
       //you get here if the button DOESN'T EXIST
       assert.isOk('everything','everything is OK');
    }
});

这篇关于赛普拉斯:如果使用IF条件,如何知道元素是否可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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