如何在Cypress中检查按钮是否处于活动状态(可点击)?

3

我想检查一个按钮是否处于激活状态(可被点击)或非激活状态(存在但不可点击)。

我尝试了以下断言,但似乎是错误的。因为第一个断言总是为真,第二个断言总是为假,无论按钮是否可点击。

cy.get('#switchdiv').should('not.be.disabled')   //clickable
cy.get('#switchdiv').should('be.disabled')       //not clickable

每种情况下的按钮HTML代码:

每种情况下的按钮HTML代码:

<button role="button" aria-disabled="false" class="styles__CTAButton-eowIhA dBjjkp switchover"></button>


<button disabled="" role="button" aria-disabled="true" class="styles__CTAButton-eowIhA dBjjkp switchover"></button>

任何帮助。谢谢。

请分享按钮在启用和禁用状态下的HTML。 - Alapan Das
我现在分享它 - Deyaa
你能分享一下你正在使用的确切按钮标签吗?你代码中分享的那些似乎没有“id”属性,因此它与测试代码的关系是不明确的。 - Warisul
@Waris 我修改了代码。 - Deyaa
2个回答

2
你可以这样做:
cy.get('#Button').then(($btn) => {
  if ($btn.is(':disabled')) {
    cy.log('Button exists and is disabled!')
    return
  } else {
    cy.log('Button exists and is enabled!')
    cy.wrap($btn).click()
  }
})

嗯,看起来问题还是一样的,我试试。这段代码总是会返回“按钮存在且已启用!”,即使按钮没有激活。 - Deyaa
我认为这可能是因为禁用的按钮是一个空字符串而不是 ":disabled"。我会在几分钟内发布另一个答案。 - agoff

1
如果Alapan的回答不起作用,你可以尝试使用aria-disabled值。这可能会解决问题。
cy.get('#Button')
  .invoke('attr', 'aria-disabled')
  .then((ariaDisabled) => {
    // Probably helpful to also cy.log() the value
    cy.log(`ariaDisabled is ${ariaDisabled}`);
    if (ariaDisabled !== "true") {
      cy.log('Button exists and is disabled!')
      return
    }
    cy.log('Button exists and is enabled!')
    cy.get('#Button').click();
  });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接