DEV Community

Diego (Relatable Code)
Diego (Relatable Code)

Posted on • Originally published at relatablecode.com on

How to make a Cypress test for prefers-color-scheme: dark

Darkmode
Photo by Terry Vlisidis on Unsplash

Taking into account the user’s preferences before the page loads are becoming more important every day to deliver the best possible experience out-of-the-box. One such option is the CSS media feature of prefers-color-scheme. This can be set up through the operating system or user agent setting.

The following is an example of how to set up dark mode through CSS:

css dark mode

As an aside I also have an article on how to quickly set up dark mode with the use of CSS variables in React, check it out here.

Cypress Test

Cypress is a testing framework that makes it super easy and fun to develop end-to-end tests! Cypress offers a function to set up variables before the page loads! We can use this to set up the preference for dark mode ahead of time.

Cypress test for dark mode

Using the onBeforeLoad function when we visit the root page we can alter what happens when we interact with the matchMedia function. matchMedia is a method on the window object that can check if the color scheme is dark. In my app I use a hook to check exactly this when applying dark mode, as its set to a variable in my global store:

Hook to set dark mode

Neat! Alright, the following parts of the Cypress test can directly look at the different CSS properties of the page to make sure everything is being applied correctly:

Additional testing for CSS properties

As an example, the app is the overall wrapper of my app. Gave it a data-testid and then I test for the color of my dark mode. This can be done several times over for all the different types of dark mode properties that are being set!

And that’s it! If you have any questions or any other preferred methods of testing out dark mode let me know in the comments below!

More content at Relatable Code

Originally published at https://relatablecode.com on December 19, 2021.

Top comments (0)