Match a CSS Class in Cypress
Ola Johansson
Posted on August 24, 2022
Another "note to self" post. Sometimes it's really hard to figure out how to assert stuff in various JS testing frameworks. Today i just wanted to check if a certain element had a CSS Class, and since i use CSS Modules i can't use "have.class" because i need to match the name. So according to Cypress documentation this is how you do it. Note that I'm also using Cypress Testing Library, i.e. the "findByText" part of this code.
cy.findByText(/english/i).should(($s) => {
expect($s).to.have.length(1);
const className = $s[0].className;
expect(className).to.match(/LanguageList_highlighted/gi);
});
Tbh it feels a bit complicated and it would of course be nice if you could just do something like cy.findByText(/english/i).should("match.class", /LanguageList_highlighted/gi)
. If anyone know a simpler way of doing this, let me know.
Posted on August 24, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.