Testing
With Vitest’s browser mode, you reset the state before each test and render the hook under the provider to check it.
On this page
Resetting between tests
color-scheme.test.tsximport { resetStateRegistry } from '@k8ordo/state';
import { beforeEach } from 'vitest';
beforeEach(() => {
localStorage.clear();
Removes the preference an earlier test stored
document.documentElement.classList.remove('dark');
Removes the class the provider’s effect added
resetStateRegistry();
Resets the @k8ordo/state stores
});localStorage, the class on <html> and the @k8ordo/state stores all persist across tests. A store is created once per key and keeps an earlier test’s values until resetStateRegistry() runs.
Note
Call resetStateRegistry() after every component using the hook is unmounted. A hook that stays mounted keeps its old store. With vitest-browser-react, the previous test’s render is cleaned up before each test.
Rendering the hook
color-scheme.test.tsximport {
ColorSchemeProvider,
colorSchemeState,
useColorScheme,
} from '@k8ordo/color-scheme';
import type { ReactNode } from 'react';
import { expect, it, vi } from 'vitest';
import { renderHook } from 'vitest-browser-react';
const wrapper = ({ children }: { children: ReactNode }) => (
<ColorSchemeProvider>{children}</ColorSchemeProvider>
);
it('starts from a stored preference', async () => {
localStorage.setItem(
colorSchemeState.storageKey,
JSON.stringify({ preference: 'dark' }),
);
const { result } = await renderHook(() => useColorScheme(), {
wrapper,
});
expect(result.current.preference).toBe('dark');
expect(result.current.scheme).toBe('dark');
expect(
document.documentElement.classList.contains('dark'),
).toBe(true);
});Calling useColorScheme() outside the provider throws an error starting with useColorScheme needs <ColorSchemeProvider> above it. Render it with the provider as renderHook’s wrapper.
Read the localStorage key from colorSchemeState.storageKey instead of spelling it out. How the key is built is up to @k8ordo/state.
Changing the preference
color-scheme.test.tsxit('stores a choice, and stores none for system', async () => {
const { result } = await renderHook(() => useColorScheme(), {
wrapper,
});
result.current.setPreference('dark');
await vi.waitFor(() => {
expect(result.current.scheme).toBe('dark');
});
expect(
document.documentElement.classList.contains('dark'),
).toBe(true);
expect(localStorage.getItem(colorSchemeState.storageKey)).toBe(
'{"preference":"dark"}',
);
result.current.setPreference('system');
await vi.waitFor(() => {
expect(result.current.preference).toBe('system');
});
expect(
localStorage.getItem(colorSchemeState.storageKey),
).toBe('{}');
});Calling setPreference does not re-render on the spot. The write to localStorage is batched to the end of the same task, and is done before the re-render.
Wait with vi.waitFor until scheme or preference changes, then check the stored value and the class.
Going back to 'system' leaves {} as the stored value. What each setPreference value stores is listed in Storage.
Dark system preference
vite.config.tsimport { playwright } from '@vitest/browser-playwright';
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
browser: {
enabled: true,
provider: playwright({
contextOptions: { colorScheme: 'dark' },
}),
instances: [{ browser: 'chromium' }],
},
},
});What 'system' resolves to depends on the test browser’s prefers-color-scheme. A browser Playwright launches prefers light unless told otherwise. To check that 'system' follows the OS setting, make the browser dark with colorScheme: 'dark' on line 9.
The setting applies to every test that runs in that browser. To check only that the hook starts from the default, a wrapper whose provider gets defaultPreference="dark" is enough.
The inline script
When it renders only in the browser with no server render, as in a test, ColorSchemeScript’s inline script does not run. React never executes an inline <script> it creates in the browser.
Rendered, it makes React’s development build log an error starting with Encountered a script tag while rendering React component. A test of the hook leaves ColorSchemeScript out and passes only the provider as the wrapper.
The class a test sees on <html> is the one the provider’s effect wrote. That the script adds the class before the first paint is covered by this package’s own tests.