polyfills.ts69 lines · main
| 1 | import { ReadableStream, TransformStream } from 'node:stream/web' |
| 2 | import { TextDecoder, TextEncoder } from 'node:util' |
| 3 | import { act } from '@testing-library/react' |
| 4 | import { configMocks } from 'jsdom-testing-mocks' |
| 5 | import { vi } from 'vitest' |
| 6 | |
| 7 | configMocks({ act }) |
| 8 | |
| 9 | // Warning: `restoreMocks: true` in vitest.config.ts will |
| 10 | // cause this global mockImplementation to be **reset** |
| 11 | // before any tests are run! |
| 12 | Object.defineProperty(window, 'matchMedia', { |
| 13 | writable: true, |
| 14 | value: vi.fn().mockImplementation((query) => ({ |
| 15 | matches: false, |
| 16 | media: query, |
| 17 | onchange: null, |
| 18 | addListener: vi.fn(), // deprecated |
| 19 | removeListener: vi.fn(), // deprecated |
| 20 | addEventListener: vi.fn(), |
| 21 | removeEventListener: vi.fn(), |
| 22 | dispatchEvent: vi.fn(), |
| 23 | })), |
| 24 | }) |
| 25 | |
| 26 | Object.defineProperties(globalThis, { |
| 27 | TextDecoder: { value: TextDecoder }, |
| 28 | TextEncoder: { value: TextEncoder }, |
| 29 | CSS: { |
| 30 | value: { |
| 31 | supports: (_k: any, _v: any) => false, |
| 32 | escape: (v: any) => v, |
| 33 | }, |
| 34 | }, |
| 35 | ReadableStream: { value: ReadableStream }, |
| 36 | TransformStream: { value: TransformStream }, |
| 37 | }) |
| 38 | |
| 39 | if (typeof window.localStorage?.getItem !== 'function') { |
| 40 | const storage = new Map<string, string>() |
| 41 | const localStoragePolyfill = { |
| 42 | getItem: vi.fn((key: string) => storage.get(key) ?? null), |
| 43 | setItem: vi.fn((key: string, value: string) => { |
| 44 | storage.set(key, value) |
| 45 | }), |
| 46 | removeItem: vi.fn((key: string) => { |
| 47 | storage.delete(key) |
| 48 | }), |
| 49 | clear: vi.fn(() => { |
| 50 | storage.clear() |
| 51 | }), |
| 52 | key: vi.fn((index: number) => Array.from(storage.keys())[index] ?? null), |
| 53 | get length() { |
| 54 | return storage.size |
| 55 | }, |
| 56 | } |
| 57 | |
| 58 | Object.defineProperty(window, 'localStorage', { |
| 59 | configurable: true, |
| 60 | value: localStoragePolyfill, |
| 61 | }) |
| 62 | |
| 63 | Object.defineProperty(globalThis, 'localStorage', { |
| 64 | configurable: true, |
| 65 | value: localStoragePolyfill, |
| 66 | }) |
| 67 | } |
| 68 | |
| 69 | window.HTMLElement.prototype.hasPointerCapture = vi.fn() |