2026-04-07 18:31:09 +08:00
|
|
|
import '@testing-library/jest-dom/vitest';
|
feat(pwa): implement real offline mode with IndexedDB sync
Add genuine offline read/write capability for trips:
- Dexie IndexedDB schema (trips, places, packing, todo, budget,
reservations, files, mutationQueue, syncMeta, blobCache)
- Repo layer for all domains: offline reads from Dexie, writes
optimistically to Dexie and enqueue mutations for later replay
- Mutation queue with UUID idempotency keys (X-Idempotency-Key),
FIFO flush, temp-ID reconciliation on 2xx, fail-and-continue on 4xx
- Trip sync manager: caches all trips with end_date >= today or null,
auto-evicts 7d after end_date, fetches bundle endpoint in one request
- Map tile prefetcher: bbox from place coords, zooms 10-16, 50MB cap,
warms SW cache via fetch
- Sync triggers: network online → flush + syncAll; WS reconnect →
flush only (rate-limiter safe); visibilitychange/30s → flush only
- WS remoteEventHandler writes through to Dexie on every event
- Server idempotency middleware + idempotency_keys table (migration 100,
24h TTL nightly cleanup)
- GET /api/trips/:id/bundle endpoint for efficient single-request sync
- OfflineBanner component: amber (offline) / blue (syncing) / hidden
- OfflineTab in Settings: cached trip list, re-sync and clear actions
- usePendingMutations hook for per-item pending indicators
Closes #505 #541
2026-04-15 05:04:13 +08:00
|
|
|
import 'fake-indexeddb/auto';
|
2026-04-07 18:31:09 +08:00
|
|
|
import { cleanup } from '@testing-library/react';
|
|
|
|
|
import { afterAll, afterEach, beforeAll, vi } from 'vitest';
|
|
|
|
|
import { server } from './helpers/msw/server';
|
|
|
|
|
|
|
|
|
|
// Mock the websocket module so stores don't try to open real connections
|
|
|
|
|
vi.mock('../src/api/websocket', () => ({
|
|
|
|
|
connect: vi.fn(),
|
|
|
|
|
disconnect: vi.fn(),
|
|
|
|
|
getSocketId: vi.fn(() => null),
|
|
|
|
|
setRefetchCallback: vi.fn(),
|
feat(pwa): implement real offline mode with IndexedDB sync
Add genuine offline read/write capability for trips:
- Dexie IndexedDB schema (trips, places, packing, todo, budget,
reservations, files, mutationQueue, syncMeta, blobCache)
- Repo layer for all domains: offline reads from Dexie, writes
optimistically to Dexie and enqueue mutations for later replay
- Mutation queue with UUID idempotency keys (X-Idempotency-Key),
FIFO flush, temp-ID reconciliation on 2xx, fail-and-continue on 4xx
- Trip sync manager: caches all trips with end_date >= today or null,
auto-evicts 7d after end_date, fetches bundle endpoint in one request
- Map tile prefetcher: bbox from place coords, zooms 10-16, 50MB cap,
warms SW cache via fetch
- Sync triggers: network online → flush + syncAll; WS reconnect →
flush only (rate-limiter safe); visibilitychange/30s → flush only
- WS remoteEventHandler writes through to Dexie on every event
- Server idempotency middleware + idempotency_keys table (migration 100,
24h TTL nightly cleanup)
- GET /api/trips/:id/bundle endpoint for efficient single-request sync
- OfflineBanner component: amber (offline) / blue (syncing) / hidden
- OfflineTab in Settings: cached trip list, re-sync and clear actions
- usePendingMutations hook for per-item pending indicators
Closes #505 #541
2026-04-15 05:04:13 +08:00
|
|
|
setPreReconnectHook: vi.fn(),
|
2026-04-07 18:31:09 +08:00
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
// MSW lifecycle
|
|
|
|
|
beforeAll(() => server.listen({ onUnhandledRequest: 'warn' }));
|
|
|
|
|
afterEach(() => {
|
|
|
|
|
server.resetHandlers();
|
|
|
|
|
cleanup();
|
|
|
|
|
localStorage.clear();
|
|
|
|
|
sessionStorage.clear();
|
|
|
|
|
});
|
|
|
|
|
afterAll(() => server.close());
|
|
|
|
|
|
|
|
|
|
// ── jsdom stubs ────────────────────────────────────────────────────────────────
|
|
|
|
|
|
2026-04-18 23:39:15 +08:00
|
|
|
// Force en-US locale for toLocaleDateString so tests are deterministic on
|
|
|
|
|
// non-US dev machines (Windows-de-DE returns "Sonntag" instead of "Sunday").
|
|
|
|
|
// Only affects calls without an explicit locale — callers that pass a locale
|
|
|
|
|
// keep their behavior.
|
|
|
|
|
const _origToLocaleDateString = Date.prototype.toLocaleDateString
|
|
|
|
|
Date.prototype.toLocaleDateString = function (locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions) {
|
|
|
|
|
return _origToLocaleDateString.call(this, locales ?? 'en-US', options)
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-07 18:31:09 +08:00
|
|
|
// window.matchMedia — used by dark mode / responsive components
|
|
|
|
|
Object.defineProperty(window, 'matchMedia', {
|
|
|
|
|
writable: true,
|
|
|
|
|
value: vi.fn().mockImplementation((query: string) => ({
|
|
|
|
|
matches: false,
|
|
|
|
|
media: query,
|
|
|
|
|
onchange: null,
|
|
|
|
|
addListener: vi.fn(),
|
|
|
|
|
removeListener: vi.fn(),
|
|
|
|
|
addEventListener: vi.fn(),
|
|
|
|
|
removeEventListener: vi.fn(),
|
|
|
|
|
dispatchEvent: vi.fn(),
|
|
|
|
|
})),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// IntersectionObserver — used by lazy loading
|
|
|
|
|
// Must use a class or regular function (not arrow function) so 'new IntersectionObserver()' works
|
|
|
|
|
class _MockIntersectionObserver {
|
|
|
|
|
observe = vi.fn()
|
|
|
|
|
unobserve = vi.fn()
|
|
|
|
|
disconnect = vi.fn()
|
|
|
|
|
root = null
|
|
|
|
|
rootMargin = ''
|
|
|
|
|
thresholds: ReadonlyArray<number> = []
|
|
|
|
|
takeRecords = vi.fn(() => [])
|
|
|
|
|
constructor(_callback: IntersectionObserverCallback, _options?: IntersectionObserverInit) {}
|
|
|
|
|
}
|
|
|
|
|
globalThis.IntersectionObserver = _MockIntersectionObserver as unknown as typeof IntersectionObserver;
|
|
|
|
|
|
|
|
|
|
// ResizeObserver — used by resizable panels
|
2026-04-22 02:21:40 +08:00
|
|
|
class _MockResizeObserver {
|
|
|
|
|
observe = vi.fn()
|
|
|
|
|
unobserve = vi.fn()
|
|
|
|
|
disconnect = vi.fn()
|
|
|
|
|
constructor(_callback: ResizeObserverCallback) {}
|
|
|
|
|
}
|
|
|
|
|
globalThis.ResizeObserver = _MockResizeObserver as unknown as typeof ResizeObserver;
|
2026-04-07 18:31:09 +08:00
|
|
|
|
2026-04-08 05:53:43 +08:00
|
|
|
// URL.createObjectURL / revokeObjectURL — Node 22 URL.createObjectURL requires
|
|
|
|
|
// a native node:buffer Blob; passing a jsdom Blob throws ERR_INVALID_ARG_TYPE.
|
|
|
|
|
// Tests that need blob URLs should mock fetch to return node:buffer Blobs so
|
|
|
|
|
// the real URL.createObjectURL works. For tests that only need the method to
|
|
|
|
|
// exist without returning a real URL, stub it here as a vi.fn fallback.
|
|
|
|
|
if (typeof URL.createObjectURL === 'undefined') {
|
|
|
|
|
Object.defineProperty(URL, 'createObjectURL', { writable: true, configurable: true, value: vi.fn(() => 'blob:mock') });
|
|
|
|
|
Object.defineProperty(URL, 'revokeObjectURL', { writable: true, configurable: true, value: vi.fn() });
|
|
|
|
|
}
|
2026-04-07 18:31:09 +08:00
|
|
|
|
|
|
|
|
// Element.prototype.scrollIntoView — jsdom doesn't implement it
|
|
|
|
|
Element.prototype.scrollIntoView = vi.fn();
|