Playwright Testing for Dark Mode and Theme Switching Applications
Test CSS custom property changes, prefers-color-scheme media queries, and theme persistence across browser sessions in themed web apps.
playwright-v1-49-matrix
Playwright Testing for Dark Mode and Theme Switching Applications
Modern web applications require thorough testing strategies that account for regional requirements, diverse user bases, and complex technical architectures. This guide provides actionable Playwright patterns for your specific context.
Introduction
Test CSS custom property changes, prefers-color-scheme media queries, and theme persistence across browser sessions in themed web apps. This guide covers the essential patterns, configurations, and strategies to handle this scenario reliably in your Playwright test suite.
Understanding the nuances of this topic allows your team to ship with confidence, reduce flakiness, and maintain high-quality automation across different environments.
Architecture Overview
graph TD
OS["OS Dark Preference"] --> Media["prefers-color-scheme"]
Media --> CSS["CSS Variables"]
CSS --> Render["Themed UI"]
Toggle["Theme Toggle"] --> LocalStorage["Persist Choice"]
LocalStorage --> Reload["Next Visit"]This structure ensures clean separation of concerns and maintainable test code.
Implementation Flow
sequenceDiagram
participant Test as Playwright Test
participant App as Application
participant API as Backend / Mock API
Test->>App: Navigate and interact
App->>API: Trigger API call
API-->>App: Return response
App-->>Test: UI state updated
Test->>Test: Assert outcomeStep-by-Step Guide
Follow this implementation to set up the pattern in your test suite.
1. Core Implementation
test('dark mode applies correct CSS colors', async ({ page }) => {
// Emulate dark mode OS preference
await page.emulateMedia({ colorScheme: 'dark' });
await page.goto('/');
const bg = await page.evaluate(() =>
window.getComputedStyle(document.body).backgroundColor
);
expect(bg).toBe('rgb(15, 23, 42)'); // Dark background
// Toggle to light mode via button
await page.getByRole('button', { name: 'Toggle theme' }).click();
const lightBg = await page.evaluate(() =>
window.getComputedStyle(document.body).backgroundColor
);
expect(lightBg).toBe('rgb(255, 255, 255)');
});2. Run and Verify
# Run this specific test file
npx playwright test --grep "Playwright Testing for"
Run with UI mode for debugging
npx playwright test --ui
Run across all browsers
npx playwright test --project=chromium --project=firefox --project=webkit3. View Test Report
npx playwright show-reportReference Table
| Test Scenario | Method | Assertion |
|---|---|---|
| OS dark mode | emulateMedia | CSS background |
| Manual toggle | click button | CSS change |
| Persistence | reload page | Theme retained |
| System sync | colorScheme change | Auto-update |
Best Practices
getByRole(), getByLabel(), and getByTestId() instead of CSS selectors for resilient tests.await expect(locator).toBeVisible() over page.waitForTimeout()Common Pitfalls
| Anti-Pattern | Problem | Solution |
page.waitForTimeout(3000) | Flaky on slow CI | Use expect(locator).toBeVisible() |
| Hardcoded selectors | Breaks on UI change | Use ARIA roles and labels |
| Shared global state | Test interference | Use isolated browser contexts |
| Real external APIs | Unreliable in CI | Mock with page.route() |
Frequently Asked Questions
How to test prefers-color-scheme with Playwright?
Use page.emulateMedia({ colorScheme: 'dark'| 'light' |
How to test theme persistence across page loads?
Set the theme, reload the page, and verify the correct theme is applied from localStorage/cookie.
Can Playwright test CSS custom property values?
Yes, use page.evaluate() to read getComputedStyle() and getPropertyValue('--custom-prop') values.
How to take dark mode visual regression screenshots?
Emulate dark mode with emulateMedia, take a screenshot with page.screenshot(), and compare against baseline.
How to test high contrast mode for accessibility?
Use emulateMedia({ forcedColors: 'active' }) to test Windows High Contrast Mode rendering.
Summary
Test CSS custom property changes, prefers-color-scheme media queries, and theme persistence across browser sessions in themed web apps. By following these patterns, your team can build a reliable, maintainable automation suite that works across environments and handles edge cases gracefully.
Related Articles
About The Author
PlaywrightPad Editorial reports on Chromium engines, E2E test optimizations, and AI integration specifications.
Newsletter
Get weekly browser reports sent directly to your inbox.