Open History to see the last commit
1import { afterEach, describe, expect, it, vi } from "vite-plus/test";
2
3function createStorage(overrides: Partial<Storage> = {}): Storage {
4 const store = new Map<string, string>();
5 return {
6 clear: () => store.clear(),
7 getItem: (key) => store.get(key) ?? null,
8 key: (index) => [...store.keys()][index] ?? null,
9 get length() {
10 return store.size;
11 },
12 removeItem: (key) => {
13 store.delete(key);
14 },
15 setItem: (key, value) => {
16 store.set(key, value);
17 },
18 ...overrides,
19 };
20}
21
22afterEach(() => {
23 vi.doUnmock("react");
24 vi.resetModules();
25 vi.restoreAllMocks();
26 vi.unstubAllGlobals();
27});
28
29describe("theme failure handling", () => {
30 it("preserves exact storage causes and operation context", async () => {
31 const readCause = new Error("storage read blocked");
32 const writeCause = new Error("storage quota exceeded");
33 vi.stubGlobal("window", {
34 localStorage: createStorage({
35 getItem: () => {
36 throw readCause;
37 },
38 setItem: () => {
39 throw writeCause;
40 },
41 }),
42 });
43
44 const { readThemePreference, ThemeStorageError, writeThemePreference } =
45 await import("./useTheme");
46
47 try {
48 readThemePreference();
49 expect.unreachable("expected the theme read to fail");
50 } catch (error) {
51 expect(error).toBeInstanceOf(ThemeStorageError);
52 expect(error).toMatchObject({
53 operation: "read",
54 storageKey: "t3code:theme",
55 cause: readCause,
56 });
57 }
58
59 try {
60 writeThemePreference("dark");
61 expect.unreachable("expected the theme write to fail");
62 } catch (error) {
63 expect(error).toBeInstanceOf(ThemeStorageError);
64 expect(error).toMatchObject({
65 operation: "write",
66 storageKey: "t3code:theme",
67 theme: "dark",
68 cause: writeCause,
69 });
70 }
71 });
72
73 it("falls back during initial theme application and logs only safe attributes", async () => {
74 const cause = new Error("private browsing storage failure");
75 const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
76 vi.stubGlobal("window", {
77 localStorage: createStorage({
78 getItem: () => {
79 throw cause;
80 },
81 }),
82 matchMedia: () => ({ matches: false }),
83 });
84 vi.stubGlobal("document", {
85 documentElement: {
86 classList: { toggle: vi.fn() },
87 },
88 });
89
90 await expect(import("./useTheme")).resolves.toBeDefined();
91
92 expect(errorLog).toHaveBeenCalledWith(
93 "Failed to read theme preference for t3code:theme.",
94 expect.objectContaining({
95 operation: "read",
96 storageKey: "t3code:theme",
97 errorTag: "ThemeStorageError",
98 }),
99 );
100 const attributes = errorLog.mock.calls[0]?.[1];
101 expect(attributes).not.toHaveProperty("cause");
102 expect(JSON.stringify(attributes)).not.toContain(cause.message);
103 });
104
105 it("retries a failed storage read only after a relevant storage event", async () => {
106 const cause = new Error("persistent storage failure");
107 const getItem = vi.fn(() => {
108 throw cause;
109 });
110 const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
111 let readSnapshot: (() => unknown) | undefined;
112 let subscribeToTheme: ((listener: () => void) => () => void) | undefined;
113 let storageHandler: ((event: StorageEvent) => void) | undefined;
114 vi.doMock("react", () => ({
115 useCallback: <A>(callback: A) => callback,
116 useEffect: () => undefined,
117 useSyncExternalStore: (
118 subscribe: (listener: () => void) => () => void,
119 getSnapshot: () => unknown,
120 ) => {
121 subscribeToTheme = subscribe;
122 readSnapshot = getSnapshot;
123 return getSnapshot();
124 },
125 }));
126 vi.stubGlobal("window", {
127 addEventListener: (type: string, listener: (event: StorageEvent) => void) => {
128 if (type === "storage") storageHandler = listener;
129 },
130 localStorage: createStorage({ getItem }),
131 matchMedia: () => ({
132 matches: false,
133 addEventListener: () => undefined,
134 removeEventListener: () => undefined,
135 }),
136 removeEventListener: () => undefined,
137 });
138
139 const { useTheme } = await import("./useTheme");
140 useTheme();
141 readSnapshot?.();
142 readSnapshot?.();
143
144 expect(getItem).toHaveBeenCalledTimes(1);
145 expect(errorLog).toHaveBeenCalledTimes(1);
146
147 const unsubscribe = subscribeToTheme?.(() => undefined);
148 storageHandler?.({ key: "t3code:theme" } as StorageEvent);
149 readSnapshot?.();
150
151 expect(getItem).toHaveBeenCalledTimes(2);
152 expect(errorLog).toHaveBeenCalledTimes(2);
153 unsubscribe?.();
154 });
155
156 it("preserves desktop sync causes and retries after a failed cosmetic sync", async () => {
157 const cause = new Error("desktop IPC unavailable");
158 const errorLog = vi.spyOn(console, "error").mockImplementation(() => {});
159 const setTheme = vi.fn().mockRejectedValue(cause);
160 vi.stubGlobal("window", { desktopBridge: { setTheme } });
161
162 const { DesktopThemeSyncError, syncDesktopTheme, syncDesktopThemePreference } =
163 await import("./useTheme");
164
165 const error = await syncDesktopThemePreference({ setTheme }, "dark").then(
166 () => undefined,
167 (failure: unknown) => failure,
168 );
169 expect(error).toBeInstanceOf(DesktopThemeSyncError);
170 expect(error).toMatchObject({ theme: "dark", cause });
171
172 setTheme.mockClear();
173 syncDesktopTheme("dark");
174 await Promise.resolve();
175 await Promise.resolve();
176 syncDesktopTheme("dark");
177 await Promise.resolve();
178 await Promise.resolve();
179
180 expect(setTheme).toHaveBeenCalledTimes(2);
181 expect(errorLog).toHaveBeenCalledWith(
182 "Failed to sync the dark theme to the desktop shell.",
183 expect.objectContaining({
184 theme: "dark",
185 errorTag: "DesktopThemeSyncError",
186 }),
187 );
188 for (const [, attributes] of errorLog.mock.calls) {
189 expect(attributes).not.toHaveProperty("cause");
190 expect(JSON.stringify(attributes)).not.toContain(cause.message);
191 }
192 });
193});