|
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; |
| 2 | + |
| 3 | +/** The theme store drives the `.dark` class + `color-scheme` off a persisted |
| 4 | + * light/dark/system preference (#107). Reset modules between cases so each gets |
| 5 | + * a fresh store initialized from the stubbed localStorage. */ |
| 6 | +describe("theme store", () => { |
| 7 | + let toggleSpy: ReturnType<typeof vi.fn>; |
| 8 | + beforeEach(() => { |
| 9 | + const store: Record<string, string> = {}; |
| 10 | + vi.stubGlobal("localStorage", { |
| 11 | + getItem: (k: string) => store[k] ?? null, |
| 12 | + setItem: (k: string, v: string) => void (store[k] = v), |
| 13 | + removeItem: (k: string) => void delete store[k], |
| 14 | + }); |
| 15 | + toggleSpy = vi.fn(); |
| 16 | + const root = { classList: { toggle: toggleSpy }, style: { colorScheme: "" } }; |
| 17 | + vi.stubGlobal("document", { documentElement: root }); |
| 18 | + vi.stubGlobal("matchMedia", () => ({ |
| 19 | + matches: false, // system → light in tests |
| 20 | + addEventListener: vi.fn(), |
| 21 | + removeEventListener: vi.fn(), |
| 22 | + })); |
| 23 | + }); |
| 24 | + afterEach(() => { |
| 25 | + vi.unstubAllGlobals(); |
| 26 | + vi.resetModules(); |
| 27 | + }); |
| 28 | + |
| 29 | + it("defaults to dark when nothing is stored", async () => { |
| 30 | + const { getTheme, resolvedTheme } = await import("./theme.ts"); |
| 31 | + expect(getTheme()).toBe("dark"); |
| 32 | + expect(resolvedTheme()).toBe("dark"); |
| 33 | + }); |
| 34 | + |
| 35 | + it("setTheme persists, applies the class, and notifies subscribers", async () => { |
| 36 | + const { setTheme, getTheme, subscribeTheme } = await import("./theme.ts"); |
| 37 | + const fn = vi.fn(); |
| 38 | + subscribeTheme(fn); |
| 39 | + setTheme("light"); |
| 40 | + expect(getTheme()).toBe("light"); |
| 41 | + expect(localStorage.getItem("pyops.theme")).toBe("light"); |
| 42 | + expect(toggleSpy).toHaveBeenCalledWith("dark", false); |
| 43 | + expect(document.documentElement.style.colorScheme).toBe("light"); |
| 44 | + expect(fn).toHaveBeenCalled(); |
| 45 | + }); |
| 46 | + |
| 47 | + it("system resolves via matchMedia (light when the OS is light)", async () => { |
| 48 | + const { setTheme, resolvedTheme } = await import("./theme.ts"); |
| 49 | + setTheme("system"); |
| 50 | + expect(resolvedTheme()).toBe("light"); |
| 51 | + expect(document.documentElement.style.colorScheme).toBe("light"); |
| 52 | + }); |
| 53 | + |
| 54 | + it("reads a stored preference on init", async () => { |
| 55 | + localStorage.setItem("pyops.theme", "light"); |
| 56 | + const { getTheme } = await import("./theme.ts"); |
| 57 | + expect(getTheme()).toBe("light"); |
| 58 | + }); |
| 59 | +}); |
0 commit comments