赛普拉斯:在使用If条件时如何知道元素是否可见?

时间:2019-08-31 11:51:11

标签: e2e-testing cypress

我想知道某个元素是否可见。我不确定该怎么做。 我知道我们可以运行此命令:

{4, 3}

但是如果元素不可见,则测试失败。因此,如果元素不可见,我只想要一个布尔值,这样我就可以确定条件。

用例:

我只想在不显示侧边栏的情况下通过单击按钮来打开侧边菜单。

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

这可能吗?

我非常感谢您的贡献。

预先感谢

1 个答案:

答案 0 :(得分:1)

Cypress允许jQuery处理DOM元素,因此对您有用:

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

更新:您需要区分现有按钮和可见按钮。下面的代码区分了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');
    }
});
相关问题