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

Cypress: How to know if element is visible or not in using If condition?

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

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

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