-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvitest.setup.ts
More file actions
85 lines (71 loc) · 2.21 KB
/
Copy pathvitest.setup.ts
File metadata and controls
85 lines (71 loc) · 2.21 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import * as matchers from '@testing-library/jest-dom/matchers';
import { cleanup } from '@testing-library/react';
import { afterEach, expect } from 'vitest';
expect.extend(matchers);
class TestStorage implements Storage {
private readonly store = new Map<string, string>();
get length(): number {
return this.store.size;
}
clear(): void {
this.store.clear();
}
getItem(key: string): string | null {
return this.store.get(key) ?? null;
}
key(index: number): string | null {
return Array.from(this.store.keys())[index] ?? null;
}
removeItem(key: string): void {
this.store.delete(key);
}
setItem(key: string, value: string): void {
this.store.set(key, value);
}
}
if (typeof window !== 'undefined') {
// Node 25 exposes an experimental global localStorage without browser
// Storage methods when no --localstorage-file path is configured.
let windowLocalStorage: Storage | undefined;
let windowSessionStorage: Storage | undefined;
try {
windowLocalStorage = window.localStorage;
windowSessionStorage = window.sessionStorage;
} catch {
windowLocalStorage = undefined;
windowSessionStorage = undefined;
}
const shouldPolyfillStorage =
typeof windowLocalStorage?.clear !== 'function' ||
typeof windowSessionStorage?.clear !== 'function';
const storageCtor = shouldPolyfillStorage ? TestStorage : window.Storage;
const localStorage = shouldPolyfillStorage ? new TestStorage() : windowLocalStorage;
const sessionStorage = shouldPolyfillStorage ? new TestStorage() : windowSessionStorage;
Object.defineProperty(globalThis, 'Storage', {
value: storageCtor,
configurable: true,
});
Object.defineProperty(globalThis, 'localStorage', {
value: localStorage,
configurable: true,
});
Object.defineProperty(globalThis, 'sessionStorage', {
value: sessionStorage,
configurable: true,
});
Object.defineProperty(window, 'Storage', {
value: storageCtor,
configurable: true,
});
Object.defineProperty(window, 'localStorage', {
value: localStorage,
configurable: true,
});
Object.defineProperty(window, 'sessionStorage', {
value: sessionStorage,
configurable: true,
});
}
afterEach(() => {
cleanup();
});