Skip to content
jshacks.dev
Testing

Test dark mode with Playwright colorScheme

Emulate prefers-color-scheme dark in Playwright with the colorScheme option or page.emulateMedia, then assert the page applies dark styles.

1 min read
Summarize in AI

CSS that follows prefers-color-scheme is hard to test by hand on every change. Playwright can switch the preference.

tests/dark.spec.jsJavaScript
import { test, expect } from '@playwright/test';

test.use({ colorScheme: 'dark' });

test('uses the dark background', async ({ page }) => {
  await page.setContent(`
    <style>
      body { background: white; }
      @media (prefers-color-scheme: dark) { body { background: rgb(17, 17, 17); } }
    </style>
    <p>Hi</p>
  `);
  await expect(page.locator('body')).toHaveCSS('background-color', 'rgb(17, 17, 17)');
});

test('can switch mid-test', async ({ page }) => {
  await page.setContent('<p>Hi</p>');
  await page.emulateMedia({ colorScheme: 'light' });
  expect(await page.evaluate(() => matchMedia('(prefers-color-scheme: dark)').matches)).toBe(false);
});
Text
Running 6 tests using 3 workers
  6 passed (1.8s)

colorScheme accepts light, dark and no-preference, and emulateMedia changes it for one page. toHaveCSS reads the computed style. See emulateMedia.

Pair it with toHaveScreenshot to catch a dark theme where text becomes unreadable.

The setting changes the media query only, so a site that stores its own theme choice in local storage or a cookie also needs that value set before the page loads. Test the toggle itself as a separate case, which checks that the saved choice wins over the system preference and survives a reload.

Share

More snippets

Debugging

Debug a single Vitest test in VS Code

Run one Vitest file under the VS Code debugger with a launch configuration that passes the open file, so breakpoints in tests and source work. Vitest 3.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.