Files
collective-lists/apps/web/tests/e2e/offline.test.ts
Oier Bravo Urtasun e7a961a66d feat(fase-2b): Realtime sync + offline queue + Modo Compra
Fase 2b closes the critical-path product differentiator. Two sessions on the
same list see each other's changes in real time, mutations survive network
drops and sync when reconnected, and a dedicated full-screen shopping view
optimises the in-store experience.

2b.1 Realtime
- `$lib/stores/realtimeSync.ts` wraps `postgres_changes` with an `applyItemEvent`
  reducer (INSERT/UPDATE/DELETE → next items[]) and a `subscribeToList` helper
  that awaits the SUBSCRIBED handshake before returning
- `/lists/[id]` subscribes in onMount, unsubscribes in onDestroy. Uses a
  `pendingTempIds` set to deduplicate own-mutation echoes against optimistic
  rows (matches by name+created_by+sort_order)
- Client-generated UUIDs for new inserts make the path idempotent: if the
  server response is lost and we retry, the second POST hits PK-conflict
  which the queue treats as success
- CHECKED section div now carries role="listitem" so Playwright locators
  follow the item across sections

2b.2 Offline queue
- `$lib/sync/queue.ts` — SyncQueue class backed by IndexedDB (idb), FIFO flush,
  MAX_ATTEMPTS=5 retry budget, PK-conflict-as-success short-circuit
- `$lib/sync/index.ts` — app-wide singleton, window.online listener flushes
  automatically, hydrateSyncState() at page load restores pendingOpsCount
- `$lib/stores/syncStatus.ts` — derived store (offline | syncing | synced)
  tracking navigator.onLine + queue depth
- SyncBanner component renders the offline/syncing indicator in the detail
  and session views
- handleAdd enqueues on failure instead of reverting, so an offline mutation
  keeps its optimistic row and syncs on reconnect

2b.3 Modo Compra
- `/lists/[id]/session/+page.svelte` — full-screen overlay (fixed inset-0
  z-50) that covers the sidebar while keeping the normal auth routing.
  56×56 toggles, flip animation shuffling items between TO BUY / CHECKED,
  Finish Shopping confirmation modal → completeList → goto('/lists')
- Link from `/lists/[id]` header (data-testid=start-session) with the
  new `list_start_session` message

Testing infra
- apps/web gets its own Vitest config (jsdom + fake-indexeddb/auto) and a
  new `pnpm test:unit` script. `just test-all` now chains pgTAP → integration
  → unit → e2e so a single command is the gate.
- packages/test-utils/tests/sync-queue.test.ts (placeholder scaffold) removed —
  replaced by `apps/web/src/lib/sync/queue.test.ts` co-located with the module

Totals: 103 tests green
  16 pgTAP
  59 Vitest integration (in packages/test-utils)
   6 Vitest unit (in apps/web — the SyncQueue)
  22 Playwright E2E (5 auth + 4 lists + 6 items + 2 realtime + 2 offline + 3 session)
   2 skipped (realtime-presence — upstream bug, unchanged)

Documented in plan/fase-2b and CLAUDE.md.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 03:32:15 +02:00

78 lines
3.0 KiB
TypeScript

/**
* O-series — Fase 2b.2 (offline-first)
*
* Uses Playwright's `context.setOffline(true)` to simulate a dropped
* connection, then verifies that:
* (a) mutations still work locally (optimistic UI + enqueue)
* (b) a banner tells the user they're offline
* (c) going back online flushes the queue and the items persist server-side
*/
import { test, expect } from '@playwright/test';
import { USERS } from '../fixtures/users.js';
import { loginAs } from '../fixtures/login.js';
const SEED_LIST_PATH = '/lists/bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
const ADD_ITEM_PLACEHOLDER = /add item|añadir producto/i;
test.describe('Offline queue + reconnect flush', () => {
test('O-01: going offline shows the banner and optimistic adds stay visible', async ({
page,
context
}) => {
await loginAs(page, USERS.borja);
await page.goto(SEED_LIST_PATH);
await expect(page.getByPlaceholder(ADD_ITEM_PLACEHOLDER)).toBeVisible({ timeout: 15_000 });
// Go offline. The SyncBanner subscribes to `navigator.onLine` via the
// isOnline store and should render within a tick.
await context.setOffline(true);
await expect(page.getByTestId('sync-banner-offline')).toBeVisible({ timeout: 3_000 });
const itemName = `O-01-${Date.now()}`;
const input = page.getByPlaceholder(ADD_ITEM_PLACEHOLDER);
await input.fill(itemName);
await input.press('Enter');
// Item renders locally even though the server call failed.
await expect(page.getByText(itemName)).toBeVisible({ timeout: 3_000 });
// Cleanup: bring the page back online so the next test starts fresh.
await context.setOffline(false);
});
test('O-02: going back online flushes the queue to the server', async ({
browser,
context
}) => {
const page = await context.newPage();
await loginAs(page, USERS.borja);
await page.goto(SEED_LIST_PATH);
await expect(page.getByPlaceholder(ADD_ITEM_PLACEHOLDER)).toBeVisible({ timeout: 15_000 });
await context.setOffline(true);
await expect(page.getByTestId('sync-banner-offline')).toBeVisible({ timeout: 3_000 });
const itemName = `O-02-${Date.now()}`;
const input = page.getByPlaceholder(ADD_ITEM_PLACEHOLDER);
await input.fill(itemName);
await input.press('Enter');
await expect(page.getByText(itemName)).toBeVisible({ timeout: 3_000 });
// Back online — the queue's 'online' listener flushes pending ops.
await context.setOffline(false);
await expect(page.getByTestId('sync-banner-offline')).not.toBeVisible({
timeout: 5_000
});
// Verify server-side persistence with a FRESH independent context:
// reload would use the same browser state; we want to prove the row
// actually made it to the DB by loading the list from a new session.
const verifyContext = await browser.newContext();
const verifyPage = await verifyContext.newPage();
await loginAs(verifyPage, USERS.ana);
await verifyPage.goto(SEED_LIST_PATH);
await expect(verifyPage.getByText(itemName)).toBeVisible({ timeout: 15_000 });
await verifyContext.close();
});
});