bonum_cete
bonum_cete

Reputation: 4962

Is there a way to check if an element has a class in cypress.io?

I don't want to test that it has the class like ...should('have.class', "some-class") I just want know if it does, and if doesn't then perform some action that gives it that class.

Basically, I want to see if the element has Mui-checked and if it doesn't them programmatically check it.

Upvotes: 4

Views: 6357

Answers (4)

colin0117
colin0117

Reputation: 1542

You can retrieve the class attribute with should() and check that it contains your class, something like:

cy.get('.selector')
  .should('have.attr', 'class')
  .and('contain', 'some-class');

Upvotes: 0

D.Zamprogna
D.Zamprogna

Reputation: 207

Colin's idea is on the right track, but .and('contain', 'some-class') still causes the test to fail (it's just a synonym for should).

Change it to .then() to check the classList:

cy.get('div')
  .should('have.attr', 'class')
  .then(classList => {
    const classes = classList.split(' ')
    if (classes.includes('some-class')) {
      // ... action when class is found
    }
  })

Note

Perform the conditional check as late as possible, in this case after .should('have.attr', 'class') which retries until the classlist is attached.

If you follow the accepted answer, you have chance of a flaky test.

Upvotes: 6

TesterDick
TesterDick

Reputation: 10535

Generally it's bad practice to do if() else() in a test.

You would want to make the test as deterministic as possible to avoid flaky tests.

In your example, if the class is added asynchronously the if() check may be executed too soon.

Instead, add the class directly. You don't need to check the condition since $el.addClass() does not fail even if the element already has the class.

cy.get('selector').then($el => $el.addClass("blue"))

Upvotes: 19

Alapan Das
Alapan Das

Reputation: 18650

You can use the hasClass() jquery method for this:

cy.get('selector').then(($ele) => {
  if ($ele.hasClass('foo')) {
    //Do something when you have the class
  } else {
    //Do something when you don't have the class
  }
})

Upvotes: 4

Related Questions