If a button is disabled then i want to skip clicking it, and if its enabled i want to click in using cypress
Asked Answered
B

2

5

I tried below code but its still trying to click the button even if its disabled and the test is getting failed.

cy.get('button').should('not.be.disabled').click()<br>
cy.get('button').should('be.enabled').click()
Burnout answered 18/11, 2020 at 8:58 Comment(4)
Hey @ashmax, can you check if this works for you cy.get('button').then(($btn) => { if ($btn.is(":disabled")) { return } else { cy.wrap($btn).click() } })Hebdomad
Can you please share the failure?Freeness
@AlapanDas your code works thankyou :)Burnout
@Burnout Happy to help. I have added this as an answer, so it can help others as well.Hebdomad
H
11

You can use the jQuery disabled-selector to achieve this. Your code should look like:

cy.get('button').then(($btn) => {
  if ($btn.is(":disabled")) {
    return
  } else {
    cy.wrap($btn).click()
  }
})
Hebdomad answered 19/11, 2020 at 18:29 Comment(0)
M
8

I suggest invoke attribute:

cy.get('button')
    .invoke('attr', 'disabled')
    .then(disabled =>{
        disabled ? cy.log('buttonIsDiabled') : cy.get('button').click()
    })
Mcdowell answered 18/11, 2020 at 9:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.