|
| 1 | +import { effectiveTheme, readTheme, writeTheme } from "../theme"; |
| 2 | + |
| 3 | +const originalLocalStorage = window.localStorage; |
| 4 | +const originalMatchMedia = window.matchMedia; |
| 5 | + |
| 6 | +function replaceLocalStorage(storage: Partial<Storage>) { |
| 7 | + Object.defineProperty(window, "localStorage", { |
| 8 | + configurable: true, |
| 9 | + value: storage, |
| 10 | + }); |
| 11 | +} |
| 12 | + |
| 13 | +afterEach(() => { |
| 14 | + Object.defineProperty(window, "localStorage", { |
| 15 | + configurable: true, |
| 16 | + value: originalLocalStorage, |
| 17 | + }); |
| 18 | + window.localStorage.clear(); |
| 19 | + window.matchMedia = originalMatchMedia; |
| 20 | + jest.restoreAllMocks(); |
| 21 | +}); |
| 22 | + |
| 23 | +describe("theme storage helpers", () => { |
| 24 | + it("round-trips valid stored themes", () => { |
| 25 | + writeTheme("dark"); |
| 26 | + |
| 27 | + expect(window.localStorage.getItem("stableroute.theme")).toBe("dark"); |
| 28 | + expect(readTheme()).toBe("dark"); |
| 29 | + }); |
| 30 | + |
| 31 | + it("falls back to system for missing or corrupted stored values", () => { |
| 32 | + expect(readTheme()).toBe("system"); |
| 33 | + |
| 34 | + window.localStorage.setItem("stableroute.theme", "midnight"); |
| 35 | + expect(readTheme()).toBe("system"); |
| 36 | + }); |
| 37 | + |
| 38 | + it("falls back to system when localStorage.getItem throws", () => { |
| 39 | + replaceLocalStorage({ |
| 40 | + getItem: jest.fn(() => { |
| 41 | + throw new Error("storage disabled"); |
| 42 | + }), |
| 43 | + }); |
| 44 | + |
| 45 | + expect(readTheme()).toBe("system"); |
| 46 | + }); |
| 47 | + |
| 48 | + it("treats write failures as a no-op", () => { |
| 49 | + const setItem = jest.fn(() => { |
| 50 | + throw new Error("quota exceeded"); |
| 51 | + }); |
| 52 | + replaceLocalStorage({ setItem }); |
| 53 | + |
| 54 | + expect(() => writeTheme("light")).not.toThrow(); |
| 55 | + expect(setItem).toHaveBeenCalledWith("stableroute.theme", "light"); |
| 56 | + }); |
| 57 | +}); |
| 58 | + |
| 59 | +describe("effectiveTheme", () => { |
| 60 | + it("returns explicit light or dark themes without media queries", () => { |
| 61 | + expect(effectiveTheme("light")).toBe("light"); |
| 62 | + expect(effectiveTheme("dark")).toBe("dark"); |
| 63 | + }); |
| 64 | + |
| 65 | + it("resolves system through prefers-color-scheme", () => { |
| 66 | + window.matchMedia = jest.fn().mockReturnValue({ matches: true }); |
| 67 | + |
| 68 | + expect(effectiveTheme("system")).toBe("dark"); |
| 69 | + expect(window.matchMedia).toHaveBeenCalledWith( |
| 70 | + "(prefers-color-scheme: dark)", |
| 71 | + ); |
| 72 | + }); |
| 73 | +}); |
0 commit comments