This guide walks you through testing your web app’s dark mode with Cypress, ensuring your UI renders correctly and remains usable when the theme is toggled. You’ll learn how to set up tests that verify the theme switch, check computed styles, and catch contrast or visibility issues early. No prior Cypress experience is required, but basic familiarity with writing tests is helpful.
What You’ll Need
- A project with Cypress installed (npm install cypress –save-dev)
- Your web app must have a dark mode toggle (CSS class, data attribute, or JS state)
- Basic knowledge of CSS selectors and assertions
Step-by-Step
- Identify how your app toggles dark mode. Inspect the toggle button or check the HTML for a class like
darkor adata-themeattribute. Note the exact selector (e.g.,#theme-toggleorbody.dark). - Create a test file. In your Cypress integration folder (usually
cypress/e2e), createdark-mode.spec.js. - Write the test skeleton. Use
describe()andit()blocks. For example:describe('Dark Mode', () => { it('toggles dark mode on', () => { ... }) }). - Visit your page. Use
cy.visit('/')to load the app. Ensure the base URL is set incypress.config.js. - Toggle dark mode. Click the toggle button with
cy.get('#theme-toggle').click(). If the toggle is a checkbox, use.check(). - Assert the theme class is applied. Check that the body or root element has the expected class:
cy.get('body').should('have.class', 'dark'). - Verify background and text colors. Get the computed styles of key elements and assert they match your dark palette. For example:
cy.get('body').should('have.css', 'background-color', 'rgb(18, 18, 18)'). Use exact RGB values from your CSS. - Check for contrast issues. If you have elements that should change color (e.g., headings, links), assert their color changed. Use
cy.get('h1').should('have.css', 'color', 'rgb(255, 255, 255)'). - Test the toggle back to light mode. Click the toggle again and assert the dark class is removed and colors revert.
- Run the test. Execute
npx cypress runin your terminal to run all tests, ornpx cypress opento run interactively.
Common Mistakes
- Assuming a single toggle button. Some apps have separate light/dark buttons or a system preference. Test each path.
- Hard-coding RGB values incorrectly. CSS colors like
#121212becomergb(18, 18, 18). Use the browser’s dev tools to copy the exact computed value. - Forgetting to wait for transitions. If your theme has a CSS transition, the computed style may not update immediately. Use
cy.wait(500)orcy.get(...).should('have.css', ...)which retries automatically. - Testing only the body. Dark mode often affects many elements. Test at least a few representative ones (header, text, button).
Tips
- Use data attributes for clarity. If you control the codebase, prefer
data-theme="dark"over ambiguous classes. - Create a custom Cypress command. For example,
cy.toggleDarkMode()to avoid repeating the toggle logic. - Take screenshots on failure. Cypress automatically captures screenshots on test failure, which helps debug visual issues.
- Test both manual toggle and system preference. If your app respects
prefers-color-scheme, simulate it withcy.visit('/', { onBeforeLoad(win) { cy.stub(win, 'matchMedia').returns({ matches: true }) } })or set the color scheme in the viewport.
Troubleshooting
If the test fails, first check that the toggle actually changes the class. Open the app manually and inspect the DOM. If the class changes but the test still fails, verify the selector you’re using is unique. If colors don’t match, ensure you’re comparing against the computed style, not the stylesheet value (e.g., a hex value becomes rgb). If the toggle is not clickable, it might be covered by another element; use cy.get('#toggle').click({ force: true }) as a temporary workaround, but fix the overlay issue in your app. Also, ensure your test runs after the page has fully loaded; add cy.waitForApp() or use cy.get('body').should('be.visible').
Frequently Asked Questions
How do I test dark mode if my app uses a CSS variable for colors?
You can assert the variable value using cy.get('body').should('have.css', '--bg-color', '#121212'). Cypress supports CSS custom properties in the have.css assertion.
Can I test dark mode in headless mode?
Yes, Cypress runs headless by default with npx cypress run. Dark mode is based on your app’s state, not the browser’s UI, so it works fine.
What if my app uses a JavaScript framework that re-renders the DOM?
Cypress automatically waits for the DOM to settle. Use cy.get() with a timeout if needed: cy.get('.dark', { timeout: 10000 }).
How do I test dark mode when the user preference is stored in localStorage?
Set localStorage before visiting the page: cy.visit('/', { onBeforeLoad: (win) => { win.localStorage.setItem('theme', 'dark') } }). Then assert the dark class is applied on load.
Can I test dark mode on multiple viewports?
Yes, use cy.viewport('iphone-x') or cy.viewport(375, 667) before asserting. Test at least one mobile and one desktop size.
Why does my test pass locally but fail in CI?
Differences in browser version or default color scheme. Set the color scheme explicitly in your test: cy.visit('/', { onBeforeLoad(win) { Object.defineProperty(win, 'matchMedia', { value: () => ({ matches: false }) }) } }) to force light mode, or use cy.visit('/', { onBeforeLoad: (win) => { win.matchMedia = () => ({ matches: true }) } }) for dark.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- Show User Library in macOS High Sierra & Sierra
- Device Manager Shortcut: Windows 10 Desktop
- How to Remove Forgotten Passcode from iPhone
- Fix Slow Wi-Fi Problem iPhone X: 9 Steps
- How to Check if a Candidate Accepts Crypto Donations
- How to Listen to Deleted Voicemails on iPhone