Home > Software engineering >  Validate button click until disabled using Cypress
Validate button click until disabled using Cypress

Time:03-10

I am trying to validate a button click using Cypress. I should be able to click on a button when there are slides available. If there are no slides the button should not be clickable and gets disabled by adding a disabled class to the button. Can anyone please suggest a better solution to validate this scenario?

Below is the HTML code when next slide is available:

<button ><span >Previous slide</span></button>

HTML code when next slide is not available and disabled class gets added:

<button ><span >Previous slide</span></button>

Cypress code that I am trying to validate:

it('Validate the button is clickable',()=> {
        cy.get('.arrow')
          .then(($btn) => {
              if($btn.is(":disabled")){
                  $btn.should('have.class','disabled')
                      .and('have.css','background-color','rgb(62, 64, 69)') 
                      cy.log('Arrow is disabled and not clickable')
              } else {
                  cy.wrap($btn).click()
                  expect($btn).to.have.css('background-color','rgb(172, 42, 0)')
              }
          })

CodePudding user response:

You can also use .hasClass('disabled') as there is a class disabled added. Also since there would multiple arrow buttons use an each instead of a then.

it('Validate the button is clickable', () => {
  cy.get('.arrow')
    .should('be.visible')
    .each(($btn) => {
      if ($btn.hasClass('disabled')) {
        cy.wrap($btn)
          .should('have.class', 'disabled')
          .and('have.css', 'background-color', 'rgb(62, 64, 69)')
        cy.log('Arrow is disabled and not clickable')
      } else {
        expect($btn).to.have.css('background-color', 'rgb(172, 42, 0)')
        cy.wrap($btn).click()
      }
    })
})
  • Related