36
<button _ngcontent-c21="" color="primary" mat-button="" class="mat-button 
mat-primary" ng-reflect-disabled="true" ng-reflect-color="primary" 
disabled=""><span class="mat-button-wrapper">

The above contains and element that can enable or disable the button depending on the user rights. I'm trying to create a test to verify whether the button is active/disabled depending on the logged in user. I'm trying to use

"expect($input).not.to.be.disabled"

but I'm not sure how to get this to work with my 'get' element (see below)

"cy.get('button.mat-button.mat-primary').eq(8)"

4 Answers 4

47

Well this was embarrassingly simple

cy.get('button.mat-button.mat-primary').eq(8).should('not.be.disabled')
cy.get('button.mat-button.mat-primary').eq(8).should('be.disabled')

and this will allow me to check if buttons are disabled or not. Didn't even need to use the "expect" route.

0
12

The Cypress documentation shows examples how you can use should() to verify elements are enabled/disabled: https://docs.cypress.io/api/commands/should.html#Assert-the-checkbox-is-disabled

cy.get(':button').should('be.disabled')
5

Your question mentioned both active and visible and they are separate as in:

  • visible / not-visible
  • active / not-active (disabled but visible)

These two different pieces of state should be considered as in:

cy.get('.mySelector').should('be.visible').click();
cy.get('.mySelector').should('be.disabled');
cy.get('.mySelector').should('not.be.disabled');
1
  • 2
    Considering the age of this question and the other answers, it would help if you were to add an explanation of why your answer is an improvement on the other answers to this question.
    – Kate Paulk
    Commented Jan 11, 2022 at 13:55
4

I recently found this code working in my case where I wanted to check if the element was enabled for next actions:

this.button().then(($btn) => {
  if ($btn.is("enabled")) {
    //do something
  } else {
    //do something else
  }
})

// in cypress terms
    cy.get(':button').then((x) => {
      if (x.is("enabled")) {
        //do something if enabled
      } else {
        //do something else
      }
    });
2
  • 2
    Are you sure that x.is('enabled') is correct? Based on this answer and my own tests, it should be !x.is(':disabled'). Commented Jul 27, 2021 at 2:52
  • I found Sasha's answer to be the best one. I was looking for how to check if an element is enabled in order to determine the next actions. Make sure to include Josh's correction, though. I needed to include Josh's correction in order to get it to work. Commented Nov 16, 2021 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.