|
7 | 7 |
|
8 | 8 | import '@testing-library/jest-dom/vitest'; |
9 | 9 | import { cleanup } from '@testing-library/react'; |
10 | | -import { afterEach } from 'vitest'; |
| 10 | +import { afterEach, beforeEach } from 'vitest'; |
| 11 | + |
| 12 | +// Node 22+ ships an experimental built-in `localStorage` that is a plain |
| 13 | +// empty object without Storage API methods. When `@vitest-environment |
| 14 | +// happy-dom` runs, that global can shadow happy-dom's Storage implementation, |
| 15 | +// leaving tests with `localStorage.getItem is not a function`. Install a |
| 16 | +// minimal in-memory Storage-compatible shim to guarantee consistent behavior |
| 17 | +// across Node versions and environments. |
| 18 | +function installStorageShim(): void { |
| 19 | + const store = new Map<string, string>(); |
| 20 | + const shim = { |
| 21 | + get length() { |
| 22 | + return store.size; |
| 23 | + }, |
| 24 | + clear(): void { |
| 25 | + store.clear(); |
| 26 | + }, |
| 27 | + getItem(key: string): string | null { |
| 28 | + return store.has(key) ? (store.get(key) as string) : null; |
| 29 | + }, |
| 30 | + setItem(key: string, value: string): void { |
| 31 | + store.set(String(key), String(value)); |
| 32 | + }, |
| 33 | + removeItem(key: string): void { |
| 34 | + store.delete(key); |
| 35 | + }, |
| 36 | + key(index: number): string | null { |
| 37 | + return Array.from(store.keys())[index] ?? null; |
| 38 | + }, |
| 39 | + }; |
| 40 | + Object.defineProperty(globalThis, 'localStorage', { |
| 41 | + configurable: true, |
| 42 | + writable: true, |
| 43 | + value: shim, |
| 44 | + }); |
| 45 | + Object.defineProperty(globalThis, 'sessionStorage', { |
| 46 | + configurable: true, |
| 47 | + writable: true, |
| 48 | + value: { ...shim }, |
| 49 | + }); |
| 50 | +} |
| 51 | + |
| 52 | +installStorageShim(); |
| 53 | + |
| 54 | +// Re-install before each test so tests that mutate localStorage.setItem |
| 55 | +// (to simulate quota errors) cannot leak across other tests. |
| 56 | +beforeEach(() => { |
| 57 | + installStorageShim(); |
| 58 | +}); |
11 | 59 |
|
12 | 60 | // Cleanup after each test |
13 | 61 | afterEach(() => { |
|
0 commit comments