setup.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. /**
  2. * Test setup file for Vitest.
  3. * Configures testing environment, mocks, and MSW server.
  4. */
  5. import '@testing-library/jest-dom';
  6. import { afterAll, afterEach, beforeAll, vi } from 'vitest';
  7. import { cleanup } from '@testing-library/react';
  8. import { server } from './mocks/server';
  9. import { batchesSettled } from '../api/batch';
  10. // Initialize i18n for tests (suppresses react-i18next warnings)
  11. import '../i18n';
  12. // Setup MSW server
  13. beforeAll(() =>
  14. server.listen({
  15. // Bypass unhandled requests silently (don't warn, just let them through)
  16. // Handlers use wildcard (*) prefix to match any origin
  17. onUnhandledRequest: 'bypass',
  18. })
  19. );
  20. afterEach(async () => {
  21. cleanup();
  22. // Let batched reads (api/batch.ts) a test started go out and be answered
  23. // before its mocks are reset, so they can't land on the next test's. Capped
  24. // so a handler a test left hanging can't stall the suite; skipped under fake
  25. // timers, which would never fire the window.
  26. if (!vi.isFakeTimers()) {
  27. await Promise.race([batchesSettled(), new Promise((resolve) => setTimeout(resolve, 200))]);
  28. }
  29. server.resetHandlers();
  30. });
  31. afterAll(() => server.close());
  32. // Mock window.matchMedia for responsive components
  33. // Uses a plain function (not vi.fn) so vi.restoreAllMocks() in tests can't wipe it
  34. Object.defineProperty(window, 'matchMedia', {
  35. writable: true,
  36. value: (query: string) => ({
  37. matches: false,
  38. media: query,
  39. onchange: null,
  40. addListener: () => {},
  41. removeListener: () => {},
  42. addEventListener: () => {},
  43. removeEventListener: () => {},
  44. dispatchEvent: () => true,
  45. }),
  46. });
  47. // Mock ResizeObserver
  48. class ResizeObserverMock {
  49. observe = vi.fn();
  50. unobserve = vi.fn();
  51. disconnect = vi.fn();
  52. }
  53. vi.stubGlobal('ResizeObserver', ResizeObserverMock);
  54. // Mock IntersectionObserver
  55. class IntersectionObserverMock {
  56. observe = vi.fn();
  57. unobserve = vi.fn();
  58. disconnect = vi.fn();
  59. root = null;
  60. rootMargin = '';
  61. thresholds = [];
  62. }
  63. vi.stubGlobal('IntersectionObserver', IntersectionObserverMock);
  64. // Mock WebSocket
  65. class MockWebSocket {
  66. static readonly CONNECTING = 0;
  67. static readonly OPEN = 1;
  68. static readonly CLOSING = 2;
  69. static readonly CLOSED = 3;
  70. readyState = MockWebSocket.OPEN;
  71. onopen: ((event: Event) => void) | null = null;
  72. onclose: ((event: CloseEvent) => void) | null = null;
  73. onmessage: ((event: MessageEvent) => void) | null = null;
  74. onerror: ((event: Event) => void) | null = null;
  75. url: string;
  76. constructor(url: string) {
  77. this.url = url;
  78. setTimeout(() => this.onopen?.(new Event('open')), 0);
  79. }
  80. send = vi.fn();
  81. close = vi.fn();
  82. }
  83. vi.stubGlobal('WebSocket', MockWebSocket);
  84. // Mock scrollTo
  85. window.scrollTo = vi.fn();
  86. // Silence jsdom's "Not implemented: navigation (except hash changes)"
  87. // warning when production code does ``window.location.href = '/setup'``
  88. // (AuthContext setup-redirect) or other full-page nav assignments.
  89. //
  90. // jsdom defines ``href`` as a non-configurable accessor on
  91. // ``Location.prototype``, so it cannot be redefined on the instance via
  92. // ``Object.defineProperty``. We wrap the real jsdom Location in a Proxy
  93. // that turns ``href = "..."`` writes into silent no-ops; everything
  94. // else (reads of ``pathname`` / ``search`` / ``hash``, writes to
  95. // ``hash``, ``assign()`` / ``replace()`` calls, ``history.replaceState``
  96. // updating ``search``) passes through unchanged. The ``get`` trap is
  97. // deliberately permissive: returning a substitute value for a non-
  98. // configurable target property violates Proxy invariants and the spread
  99. // operator (``{ ...window.location }``) walks every key — tests that
  100. // use the spread to copy the location object must keep working.
  101. {
  102. const realLocation = window.location;
  103. const locationProxy = new Proxy(realLocation, {
  104. set(target, prop, value) {
  105. if (prop === 'href') {
  106. // Silently swallow "navigation not implemented". Tests asserting
  107. // on the redirect should replace ``window.location`` themselves
  108. // (several existing tests do exactly this).
  109. return true;
  110. }
  111. Reflect.set(target, prop, value);
  112. return true;
  113. },
  114. get(target, prop, receiver) {
  115. // Return the exact value present on the target. Returning a
  116. // bound/wrapped version of a non-configurable function (``assign``
  117. // is one) violates Proxy invariants (the spread operator at one
  118. // call site triggers this). Production code that does
  119. // ``window.location.assign(url)`` calls the function with the
  120. // proxy as ``this``, which jsdom still accepts because its
  121. // Location methods unwrap their receiver internally.
  122. return Reflect.get(target, prop, receiver);
  123. },
  124. });
  125. Object.defineProperty(window, 'location', {
  126. configurable: true,
  127. writable: true,
  128. value: locationProxy,
  129. });
  130. }
  131. // jsdom has no scrolling: a page that scrolls to an element on a timer (an
  132. // archive link scrolls to its card) would throw after the test that caused it
  133. // has ended. Tests that check the scroll stub it themselves.
  134. if (!Element.prototype.scrollIntoView) {
  135. Element.prototype.scrollIntoView = () => {};
  136. }
  137. // Mock localStorage
  138. const localStorageMock = {
  139. getItem: vi.fn(),
  140. setItem: vi.fn(),
  141. removeItem: vi.fn(),
  142. clear: vi.fn(),
  143. };
  144. Object.defineProperty(window, 'localStorage', { value: localStorageMock });
  145. // Suppress console output during tests (reduces noise)
  146. // Remove these lines if you need to debug test output
  147. vi.spyOn(console, 'log').mockImplementation(() => {});
  148. vi.spyOn(console, 'warn').mockImplementation(() => {});
  149. vi.spyOn(console, 'error').mockImplementation(() => {});