Search code examples
javascriptcypresscypress-cucumber-preprocessor

Cypress/Javascript - how to wait for a element to not have a class?


I am having a little issue with my javacript/cypress code.

What I am trying to do is that if the user clicks on a button (it's an <a> link in the html further below) then wait until the class selectionAdded is removed from the dom with that <a> link.

Let me show you what I mean. Here is the button:

<a class="oddsBoostedPrice   button__bet eventSelection--link" "="">

Click on the button and a class appears briefly known as .selectionAdded (represents the front end as the 'Added' text hovering over the button).

<a class="oddsBoostedPrice   button__bet eventSelection--link selectionAdded" "="">

After a few moments, the 'Added' hover disappears from the button and so the element now looks like this (.selected class is added but more importantly it's back to a clickable state which only happens once .selectionAdded is removed from the dom).

<a class="oddsBoostedPrice   button__bet eventSelection--link selected" "="">

So basically my logic below is basically stating find an element that's not already selected, click on it, break from loop and then wait for element to not contain class selectionAdded (to ensure button is clickable state as later on I will click the same button).

const oddsSelectionElements = new OddsSelectionElements();

When ("User selects an available bet bundle selection", () => {
  oddsSelectionElements.oddsButton().each((element, index) => {
      if (element.not("have.class", "selected")) {
      oddsSelectionElements.selectionName().eq(index).invoke("text").then(formatters.formatString).as("selectionName");
      cy.wrap(element).click();
      return false;
    }
  })
   oddsSelectionElements.oddsButton().not("have.class", "selectionAdded"); 
})

class OddsSelectionElements

class OddsSelectionElements {

    oddsButton() {
        return cy.get('.button__bet')
    }
 
}

export default OddsSelectionElements

My issue is that my test is flakey and it looks like it's because sometimes later on the test, it clicks the button when it's not in a clickable state and I believe it's because it's not waiting until the button does not have that selectionAdded class.

What needs to happen to fix this?


Solution

  • Ok, to fix this you can add timeouts. This can be local to a single command or global as well. By default, cypress has a timeout of 4 seconds

    To apply timeout locally, you can do something like this:

    //timeout for 7 seconds
    cy.get('selector', { timeout: 7000 }).("have.class", "selectionAdded")  
    

    Or, if you want to increase the timeout globally for all commands, Go to cypress.json and add:

    defaultCommandTimeout: 7000
    

    Also please change:

    oddsSelectionElements.oddsButton().("not.have.class", "selectionAdded")