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.

AWS Q Developer image

Your AI Code Assistant

Implement features, document your code, or refactor your projects.
Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay