polyfills.ts 1.9 KB

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