如何检查柏树中的按钮是否处于活动状态(可以单击)?

how to check if button is active (can be clicked) in cypress?

我想检查一个按钮是激活的(可以点击)还是不激活的(存在但不可点击)。

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

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

每种情况下按钮的 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>

任何帮助。谢谢

你可以这样做:

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

如果 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();
  });