BruceyBandit
BruceyBandit

Reputation: 4324

Cypress/Javascript - Trying to click on a button that is not already selected

I am having issue in my cypress where I am trying to click on a second button that is not disabled or selected already. What is happening currently is that it is selecting the already selected button and I am not sure why this is.

Here is a html example, so if you look at the code below, there are two divs which each handle a selection row. Within each row is a button (<a> link).

So what happens is that if a button is selected, the class selected is added onto the <a> element like so:

<a id="event-selection-4191929065" eventid="event-selection-19976412" title="Ronaldo to score 2 or more goals" eventmodule="ODDS_BOOSTS_HOMEPAGE" class="oddsBoostedPrice   button__bet eventSelection--link selected" "="">

That's why I have the check to make sure we go through each odds button element and if it does not contain the .selected class.

Can anyone see what I am doing wrong and how to fix this?

Upvotes: 1

Views: 332

Answers (2)

Alapan Das
Alapan Das

Reputation: 18650

You can try changing your if condition to something like this:

oddsSelectionElements.oddsButton().each((element, index) => {
  if (!element.prop("disabled") && !element.hasClass("selected")) {
    cy.wrap(element).click()
    return false
  }
})

Upvotes: 1

Michael Hines
Michael Hines

Reputation: 1098

This one can be simplified, because you already check class .button__bet inside oddsButton method.

oddsSelectionElements.oddsButton()
  .each((element, index) => {
    if (!element.hasClass("disabled") && !element.hasClass("selected")) {
      cy.wrap(element).click()
      return false
    }
  })

Sorry, it needs && between the two class checks because each check is ! (not).


disabled is usually an attribute, which would be checked like this

oddsSelectionElements.oddsButton()
  .each((element, index) => {
    if (!element.attr("disabled") && !element.hasClass("selected")) {
      cy.wrap(element).click()
      return false
    }
  })

Tested with this HTML fragment

<button class="oddsBoostedPrice   button__bet eventSelection--link selected"></button>
<button class="oddsBoostedPrice   button__bet eventSelection--link" disabled></button>
<button class="oddsBoostedPrice   button__bet eventSelection--link"></button>

Only the 3rd button passes into the if() statement.

Upvotes: 2

Related Questions