How to Check if Your Buttons Are Disabled or Not In Cypress

How to Check if Your Buttons Are Disabled or Not In Cypress

Ferenc Almasi β€’ 2022 August 16 β€’ Read time 2 min read
  • twitter
  • facebook

To check if your buttons are disabled in Cypress or not, you can use the should('be.disabled') or should('not.be.enabled') assertions.

Copied to clipboard!
cy.get('button').should('be.disabled')
cy.get('button').should('not.be.enabled')

Generally speaking, reading positive conditions is easier to read, therefore from a readability standpoint, should('be.disabled') is the preferred way.

You can also check the opposite and see if your buttons are enabled by negating the assertions in the following way:

Copied to clipboard!
cy.get('button').should('not.be.disabled')
cy.get('button').should('be.enabled')

Checking if button should not be disabled

Checking for aria attributes in Cypress

In case you need to also check if your buttons have the proper aria-disabled attributes set to test accessibility, you can use the should('have.attr') assertion.

Copied to clipboard! Playground
// Check if the attribute is present
cy.get('button').should('have.attr', 'aria-disabled')

// Check the value of the attribute as well
cy.get('button').should('have.attr', 'aria-disabled', 'true')
cy.get('button').should('have.attr', 'aria-disabled', 'false')

Notice that the third boolean parameter is also passed a string since the value of the attribute will be a string as well.


Enabling disabled buttons in Cypress

In case you need to enable disabled buttons in Cypress for testing purposes, you can use the invoke command:

Copied to clipboard!
cy.get('button').invoke('prop', 'disabled', false)
Enabling disabled button in Cypress

Using invoke('prop') you can access all the available DOM properties on DOM elements, and either get their values (by passing only the first two parameters) or set their values (by passing the third value). Notice that you need to chain the invoke command from an element after grabbing it with cy.get.

Want to learn Cypress from end to end? Check out my Cypress course on Educative where I cover everything:

Learn Cypress with Educative
How to Check if Your Buttons Are Disabled or Not In Cypress
If you would like to see more webtips, follow @flowforfrank
Looking to improve your skills? Check out our interactive course to master Cypress from start to finish.
Master Cypressinfo Remove ads

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.