How to Check if Your Buttons Are Disabled or Not In Cypress
To check if your buttons are disabled in Cypress or not, you can use the should('be.disabled')
or should('not.be.enabled')
assertions.
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:
cy.get('button').should('not.be.disabled')
cy.get('button').should('be.enabled')
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.
// 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:
cy.get('button').invoke('prop', 'disabled', false)
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:
Resources:
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: