-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvitest-setup.ts
More file actions
66 lines (58 loc) · 1.59 KB
/
vitest-setup.ts
File metadata and controls
66 lines (58 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* @file Vitest setup file for configuring testing environment
*/
import "@testing-library/jest-dom/vitest";
type StorageLike = {
getItem: (key: string) => string | null;
setItem: (key: string, value: string) => void;
removeItem: (key: string) => void;
clear: () => void;
key: (index: number) => string | null;
readonly length: number;
};
const isStorageLike = (value: unknown): value is StorageLike => {
if (!value || typeof value !== "object") {
return false;
}
const candidate = value as Partial<StorageLike>;
return (
typeof candidate.getItem === "function" &&
typeof candidate.setItem === "function" &&
typeof candidate.removeItem === "function" &&
typeof candidate.key === "function"
);
};
const createMemoryStorage = (): StorageLike => {
const store = new Map<string, string>();
const getKeyAt = (index: number): string | null => {
const keys = Array.from(store.keys());
return keys[index] ?? null;
};
return {
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => {
store.set(key, value);
},
removeItem: (key) => {
store.delete(key);
},
clear: () => {
store.clear();
},
key: (index) => getKeyAt(index),
get length() {
return store.size;
},
};
};
const ensureLocalStorage = (): void => {
const current = globalThis.localStorage as unknown;
if (isStorageLike(current) && typeof current.clear === "function") {
return;
}
Object.defineProperty(globalThis, "localStorage", {
value: createMemoryStorage(),
configurable: true,
});
};
ensureLocalStorage();