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

Top comments (0)