Relatable Code

Back

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

β€’ 2 min read

Introduction

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!

If you see any typos or errors you can edit the article directly on GitHub

Hi, I'm Diego Ballesteros πŸ‘‹.

Stay on top of the tech industry and grow as a developerwith a curated selection of articles and news alongside personal advice, observations, and insight. πŸš€

No spam πŸ™…β€β™‚οΈ. Unsubscribe whenever.

Envelope
Subscribe

You may also like these articles: