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.
CSS that follows prefers-color-scheme is hard to test by hand on every change. Playwright can switch the preference.
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);
});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.