DEV Community

Ola Johansson
Ola Johansson

Posted on • Edited on

Match a CSS Class in Cypress

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);
        });
Enter fullscreen mode Exit fullscreen mode

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more