Test dynamic class names from CSS Modules in Cypress

olaj

Ola Johansson

Posted on September 23, 2022

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

💖 💪 🙅 🚩
olaj
Ola Johansson

Posted on September 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related