DEV Community

Ola Johansson
Ola Johansson

Posted on

Test dynamic class names from CSS Modules in Cypress

Sometimes you want to test that a element in your code get the correct CSS class. I use CSS Modules so it's impossible to know the exact class name when you writing the test.

Sometimes i have worked around this issue by asserting directly against the actual css i.e

    cy.findByText(/my text/gi)
      .should("have.css", "background-color", "rgb(60, 99, 132)")
      .should("have.attr", "href")
      .and("include", "about"); 
Enter fullscreen mode Exit fullscreen mode

This works, but usually it's not really the color your after but if for example a element is active or focused or something.

And today i did some digging and finally found how to do this. Really simple tbh.

    cy.findByText(/my text/gi)
      .invoke("attr", "class")
      .should("contain", "selected");

    cy.findByText(/my text/gi)
      .should("have.attr", "href")
      .and("include", "about");
Enter fullscreen mode Exit fullscreen mode

Note that i use Testing Library for Cypress to get that "findByText" method. But this should also work for regular cypress "cy.get" commands.

Reference: Github Issue Comment

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

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

👋 Kindness is contagious

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

Okay