Sub topic 12
Testing Both Themes in Developer Tools
This chapter assumes you have built the theme from the earlier chapters. That means CSS custom properties for colors, a prefers-color-scheme media query, color-scheme: light dark, and a toggle that sets data-theme and saves the choice in localStorage. You should be comfortable opening browser developer tools and reading the Elements and Console panels.
Dark mode has more states than most CSS features. A page can look wrong in only one combination of system setting and saved choice, and you may never see that combination on your own machine. This chapter shows how to force each state, inspect what the browser computed, and catch the failures that people commonly report.
What You Are Testing
Two inputs decide which theme a visitor sees:
- The system setting, which the browser exposes through
prefers-color-scheme. - The saved choice, which your script stores in
localStorageand applies asdata-themeon the root element.
Because the saved choice can be absent, light, or dark, and the system can be light or dark, there are six combinations to check.
| System setting | Saved choice | Expected result |
|---|---|---|
| Light | None | Light |
| Dark | None | Dark |
| Light | `light` | Light |
| Dark | `light` | Light (explicit choice wins) |
| Light | `dark` | Dark (explicit choice wins) |
| Dark | `dark` | Dark |
The two rows where the saved choice disagrees with the system are the ones most often broken. You can only reach them reliably by emulating the system setting instead of changing your operating system.
Emulating the System Setting
Every major browser can override the prefers-color-scheme value without touching your operating system. The override affects the media query, color-scheme-based UI such as form controls and scrollbars, and light-dark().
Chrome and Edge
- Open DevTools and press Ctrl+Shift+P (Cmd+Shift+P on macOS) to open the command menu.
- Type "Show Rendering" and press Enter.
- Find "Emulate CSS media feature prefers-color-scheme" and choose
prefers-color-scheme: darkorprefers-color-scheme: light.
The same Rendering tab has "Emulate auto dark mode". That option makes Chromium darken pages that have no dark theme. Leave it off when you test your own theme, because it can hide missing dark styles by darkening them automatically.
Firefox
The Inspector's Rules panel toolbar has two small buttons with sun and moon icons. They simulate prefers-color-scheme: light and dark. Click the active button again to stop simulating.
Safari
Open the Web Inspector from the Develop menu and go to the Elements tab. It has an appearance button that forces the page to render in light or dark. The label differs between Safari versions, so look for the sun or moon style control.
What emulation does not change
Emulation changes only the media feature. It does not change data-theme, and it does not touch localStorage. If a saved dark choice exists, the page stays dark when you emulate light. That is correct behavior, but it can look like a failed test if you forgot the saved value was there.
Checking from the Console
The console lets you ask the browser what it believes. This snippet reports the system value, the attribute, the stored value, and the colors that were actually computed.
(function reportTheme() {
const root = document.documentElement;
const style = getComputedStyle(document.body);
console.table({
systemPrefersDark: window.matchMedia("(prefers-color-scheme: dark)").matches,
dataTheme: root.dataset.theme ?? "(not set)",
saved: localStorage.getItem("theme") ?? "(none)",
colorScheme: getComputedStyle(root).colorScheme,
background: style.backgroundColor,
text: style.color
});
})();Paste it, change a setting, and run it again. If systemPrefersDark does not change when you switch the emulation, the emulation is not active. If background is rgb(255, 255, 255) while you expected dark, the bug is in your CSS, not your test setup.
To watch the system value change live, add a listener:
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", (event) => {
console.log("System is now", event.matches ? "dark" : "light");
});If your page has code that reacts to this event, for example a canvas chart that must redraw, this listener confirms the event fires when you flip the emulation.
Testing the Manual Toggle and Stored Choice
Work through the table above in this order:
- In DevTools, open Application (Chrome and Edge) or Storage (Firefox) and clear the
themeentry under Local Storage. - Emulate light and reload. Confirm light. Emulate dark and confirm dark. This tests the pure system path.
- Click your toggle to choose light while the system is emulated as dark. Confirm the page turns light and
data-theme="light"appears on the<html>element in the Elements panel. - Reload. The page should stay light, and the
themeentry in Local Storage should readlight. - Repeat with the opposite pairing.
You can also edit the attribute directly. In the Elements panel, double-click the data-theme attribute on <html> and type dark. This is faster than clicking the toggle, and it tests the CSS without involving your script. When this works but the toggle does not, the bug is in the JavaScript.
Watching the cascade
Select <html> and look at the Styles pane. With data-theme="light" and a dark system, the @media (prefers-color-scheme: dark) block should appear crossed out or absent, because :root:not([data-theme="light"]) no longer matches. If the dark block still applies, your selector is probably missing the :not() part.
Catching the Flash of the Wrong Theme
A flash happens when the page paints with the default colors before the head script runs, or when the script sits at the end of <body>. On a fast development machine it is easy to miss. Slow it down:
- Set a saved choice that disagrees with the system, for example saved
darkwith the system emulated as light. - In the Network panel, tick "Disable cache" and choose a slow preset such as "Slow 4G" (or "Slow 3G" in older versions).
- Reload and watch the first paint.
For a frame-by-frame record, open the Performance panel, enable Screenshots, click the reload-and-record button, and inspect the earliest screenshots. A white frame followed by a dark one confirms the flash.
Common causes are the theme script loaded with defer or async, the script placed after the stylesheet-dependent content, and the script reading localStorage after a DOMContentLoaded handler. The inline script in <head> from the earlier chapter avoids all three.
Testing without JavaScript
Open the command menu and run "Disable JavaScript", then reload. A visitor without scripts should still get the system theme, because the media query does not need JavaScript. The toggle will do nothing, which is acceptable, but the colors must still match the system setting.
Inspecting Tokens and Contrast
With a theme active, select any element and open the Computed tab. Tick "Show all" and filter by -- to see custom properties resolved for that element. This confirms which value a token actually received.
For contrast, click a color swatch next to color in the Styles pane. The color picker shows the contrast ratio against the background and marks the AA and AAA thresholds with lines. Check body text, links, placeholder text, and disabled controls in both themes. Run this check once per emulated scheme, because a token that passes in light can fail in dark.
The Lighthouse accessibility audit and the Issues panel also report low-contrast text. Treat them as a second opinion and not as a complete check. They sample what is rendered at that moment, so hover states, focus rings, and elements inside collapsed sections need a manual look.
Automating the Matrix
Checking six states by hand is tedious after each change. Playwright can emulate the color scheme and seed localStorage before any page script runs. This test assumes your page is served at http://localhost:8080/, uses the tokens #ffffff and #121212 from earlier chapters, and runs with npx playwright test.
import { test, expect } from "@playwright/test";
const url = "http://localhost:8080/";
const LIGHT = "rgb(255, 255, 255)";
const DARK = "rgb(18, 18, 18)";
const cases = [
{ system: "light", saved: null, expected: LIGHT },
{ system: "dark", saved: null, expected: DARK },
{ system: "light", saved: "light", expected: LIGHT },
{ system: "dark", saved: "light", expected: LIGHT },
{ system: "light", saved: "dark", expected: DARK },
{ system: "dark", saved: "dark", expected: DARK }
];
for (const { system, saved, expected } of cases) {
test(`system ${system}, saved ${saved}`, async ({ page }) => {
await page.emulateMedia({ colorScheme: system });
await page.addInitScript((value) => {
if (value) localStorage.setItem("theme", value);
}, saved);
await page.goto(url);
const background = await page.evaluate(
() => getComputedStyle(document.body).backgroundColor
);
expect(background).toBe(expected);
});
}Playwright starts a fresh browser context for each test, so storage from one case never leaks into the next.
Common Errors
- The page ignores the emulation. The
<html>element has adata-themeset from an earlier session. Clear Local Storage and reload. - Emulation seems to reset. Closing DevTools usually ends the emulation. Reopen DevTools and set it again.
- Form controls and scrollbars stay light in dark mode.
color-scheme: light darkis missing from:root, or it is overridden bycolor-scheme: lightin a rule that still matches. - Only the first load is correct. The toggle updates
data-themebut notlocalStorage, or the head script runs before the key is written under a different name. Compare the key string in both places. - The test passes in DevTools but the real phone differs. Browsers cache stylesheets and scripts. Retest with "Disable cache" ticked, then on a real device with its system setting changed.
- Images look wrong only in dark. The emulation applies to
<picture>sources too. Check each image and logo in both schemes.
Exercise
Your page has a saved choice of dark in Local Storage. You emulate prefers-color-scheme: light in DevTools and the page stays dark. Is this a bug? How would you test the system-only behavior?
Show answer
It is not a bug. Emulation changes only the media feature, and the explicit data-theme="dark" set from the saved choice outranks the system setting. To test the system-only path, delete the theme entry from Local Storage, remove the data-theme attribute from <html> (or reload after clearing storage), and then emulate light and dark.
Exercise
Using the Playwright example, which two entries in the cases array verify that an explicit choice overrides the system setting, and what would you check if the entry with system dark and saved light failed?
Show answer
The entries with system dark and saved light, and with system light and saved dark. If the first one failed, check that the dark media query is written as :root:not([data-theme="light"]) so it stops matching when data-theme="light" is set, and check that the head script reads the theme key and sets the attribute before first paint.