Reputation: 4962
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
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
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
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
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