setup.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import '@testing-library/jest-dom/vitest'
  2. import { cleanup } from '@testing-library/react'
  3. import { afterAll, afterEach, beforeAll, beforeEach } from 'vitest'
  4. import { setupBrowserMocks, cleanupBrowserMocks } from './mocks/browser'
  5. import { setupMockWebSocket, cleanupMockWebSocket } from './mocks/websocket'
  6. import { server } from './mocks/server'
  7. import { resetMockData, resetApiCallLog } from './mocks/handlers'
  8. import { apiClient } from '@/lib/apiClient'
  9. // Stub WebSocket at MODULE scope, not in beforeAll: useStatusStore opens its
  10. // socket at import time, which happens before beforeAll runs. Node's native
  11. // WebSocket would otherwise connect to a real dev backend on this machine
  12. // (if one is running) and its live status pushes would clobber seeded test
  13. // state — making the suite pass or fail depending on what's running locally.
  14. setupMockWebSocket()
  15. // Setup browser mocks FIRST (before MSW starts)
  16. // This ensures WebSocket mock is in place before MSW tries to intercept
  17. beforeAll(() => {
  18. setupBrowserMocks()
  19. // Use 'warn' instead of 'error' to avoid failing on WebSocket requests
  20. // that are handled by our mock WebSocket, not MSW
  21. server.listen({ onUnhandledRequest: 'warn' })
  22. })
  23. // Reset state between tests
  24. beforeEach(() => {
  25. resetMockData()
  26. resetApiCallLog()
  27. // Cross-test pollution guards: TableContext persists tables/active-id to
  28. // localStorage, and apiClient's base URL is module state. A leftover base
  29. // URL makes TableProvider call setBaseUrl on a later mount, which fires
  30. // onBaseUrlChange and wipes the status store mid-test (seeded statuses
  31. // vanish, connection-gated buttons disable). Reset both up front — this
  32. // runs before each file's own beforeEach, so seeds applied there survive.
  33. localStorage.clear()
  34. apiClient.setBaseUrl('')
  35. })
  36. // Cleanup after each test
  37. afterEach(() => {
  38. cleanup()
  39. server.resetHandlers()
  40. })
  41. // Teardown after all tests
  42. afterAll(() => {
  43. server.close()
  44. cleanupMockWebSocket()
  45. cleanupBrowserMocks()
  46. })