Skip to content

Commit de882dc

Browse files
authored
🐛 修正 localStorage mock (#1382)
1 parent 2c56198 commit de882dc

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

tests/vitest.setup.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,35 @@ import { MockBlob } from "./mocks/blob";
77
import { MockResponse } from "./mocks/response";
88
import { mockFetch } from "./mocks/fetch";
99

10+
function createStorageMock(): Storage {
11+
const store = new Map<string, string>();
12+
return new Proxy(
13+
{
14+
getItem: (k: string) => store.get(k) ?? null,
15+
setItem: (k: string, v: string) => void store.set(String(k), String(v)),
16+
removeItem: (k: string) => void store.delete(k),
17+
clear: () => store.clear(),
18+
key: (i: number) => [...store.keys()][i] ?? null,
19+
} as Storage,
20+
{
21+
get: (t, p) => (p === "length" ? store.size : p in t ? (t as any)[p] : store.get(p as string)),
22+
set: (t, p, v) => (p in t ? false : (store.set(p as string, String(v)), true)),
23+
deleteProperty: (_, p) => store.delete(p as string),
24+
has: (t, p) => p in t || p === "length" || store.has(p as string),
25+
ownKeys: () => [...store.keys()],
26+
getOwnPropertyDescriptor: (_, p) =>
27+
store.has(p as string)
28+
? { value: store.get(p as string), writable: true, enumerable: true, configurable: true }
29+
: undefined,
30+
}
31+
);
32+
}
33+
34+
// Ensure localStorage exists
35+
if (typeof window !== "undefined" && !global.localStorage?.getItem) {
36+
vi.stubGlobal("localStorage", createStorageMock());
37+
}
38+
1039
vi.stubGlobal("chrome", chromeMock);
1140
chromeMock.init();
1241
initTestEnv();

0 commit comments

Comments
 (0)