|
| 1 | +/** |
| 2 | + * useQueuedCheckIn — behaviour coverage via a harness component. |
| 3 | + * |
| 4 | + * `useCheckIn` and the resilience connection API are mocked and driven |
| 5 | + * per test; the real localStorage-backed outbox runs underneath so the |
| 6 | + * queue/flush round-trip is genuinely exercised. |
| 7 | + */ |
| 8 | +import { describe, it, expect, vi, beforeEach } from 'vitest'; |
| 9 | +import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'; |
| 10 | +import type { ReactNode } from 'react'; |
| 11 | +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; |
| 12 | + |
| 13 | +// ── i18n stub (useMutationToast reads useTranslation) ── |
| 14 | +vi.mock('react-i18next', () => { |
| 15 | + const t = (key: string, vars?: Record<string, unknown>): string => { |
| 16 | + if (vars && typeof vars.defaultValue === 'string') { |
| 17 | + let s: string = vars.defaultValue; |
| 18 | + for (const [k, v] of Object.entries(vars)) { |
| 19 | + if (k === 'defaultValue') continue; |
| 20 | + s = s.replace(new RegExp(`{{\\s*${k}\\s*}}`, 'g'), String(v)); |
| 21 | + } |
| 22 | + return s; |
| 23 | + } |
| 24 | + return key; |
| 25 | + }; |
| 26 | + return { |
| 27 | + useTranslation: () => ({ t, i18n: { language: 'en', changeLanguage: vi.fn() } }), |
| 28 | + Trans: ({ children }: { children?: ReactNode }) => <>{children}</>, |
| 29 | + initReactI18next: { type: '3rdParty', init: () => undefined }, |
| 30 | + }; |
| 31 | +}); |
| 32 | + |
| 33 | +vi.mock('@/api/hooks/useJourney', () => ({ |
| 34 | + useCheckIn: vi.fn(), |
| 35 | +})); |
| 36 | + |
| 37 | +vi.mock('@/api/hooks/_toastHelpers', () => ({ |
| 38 | + useMutationToast: () => ({ success: vi.fn(), warning: vi.fn(), error: vi.fn() }), |
| 39 | +})); |
| 40 | + |
| 41 | +const statusState = { |
| 42 | + status: 'online' as 'online' | 'offline', |
| 43 | + listeners: new Set<(s: 'online' | 'offline') => void>(), |
| 44 | +}; |
| 45 | + |
| 46 | +vi.mock('@/lib/resilience', async (importOriginal) => { |
| 47 | + const original = await importOriginal<typeof import('@/lib/resilience')>(); |
| 48 | + return { |
| 49 | + ...original, |
| 50 | + getConnectionStatus: () => statusState.status, |
| 51 | + onStatusChange: (fn: (s: 'online' | 'offline') => void) => { |
| 52 | + statusState.listeners.add(fn); |
| 53 | + return () => { |
| 54 | + statusState.listeners.delete(fn); |
| 55 | + }; |
| 56 | + }, |
| 57 | + }; |
| 58 | +}); |
| 59 | + |
| 60 | +function setStatus(s: 'online' | 'offline') { |
| 61 | + statusState.status = s; |
| 62 | + statusState.listeners.forEach((fn) => fn(s)); |
| 63 | +} |
| 64 | + |
| 65 | +import { useCheckIn } from '@/api/hooks/useJourney'; |
| 66 | +import { useQueuedCheckIn } from './useQueuedCheckIn'; |
| 67 | +import { enqueueCheckIn, loadOutbox } from '../lib/checkInOutbox'; |
| 68 | + |
| 69 | +const mockCheckIn = useCheckIn as unknown as ReturnType<typeof vi.fn>; |
| 70 | + |
| 71 | +function Harness({ sessionId = 1 }: { sessionId?: number }) { |
| 72 | + const { checkIn, queued, isPending } = useQueuedCheckIn(sessionId); |
| 73 | + return ( |
| 74 | + <div> |
| 75 | + <button type="button" onClick={checkIn} disabled={isPending}> |
| 76 | + tap |
| 77 | + </button> |
| 78 | + <span data-testid="queued">{queued}</span> |
| 79 | + </div> |
| 80 | + ); |
| 81 | +} |
| 82 | + |
| 83 | +function renderHarness(sessionId?: number) { |
| 84 | + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); |
| 85 | + return render( |
| 86 | + <QueryClientProvider client={client}> |
| 87 | + <Harness sessionId={sessionId} /> |
| 88 | + </QueryClientProvider>, |
| 89 | + ); |
| 90 | +} |
| 91 | + |
| 92 | +beforeEach(() => { |
| 93 | + vi.clearAllMocks(); |
| 94 | + localStorage.clear(); |
| 95 | + statusState.status = 'online'; |
| 96 | + statusState.listeners.clear(); |
| 97 | + mockCheckIn.mockReturnValue({ mutate: vi.fn(), mutateAsync: vi.fn(), isPending: false }); |
| 98 | +}); |
| 99 | + |
| 100 | +describe('useQueuedCheckIn', () => { |
| 101 | + it('sends immediately when online', () => { |
| 102 | + const mutate = vi.fn(); |
| 103 | + mockCheckIn.mockReturnValue({ mutate, mutateAsync: vi.fn(), isPending: false }); |
| 104 | + renderHarness(); |
| 105 | + fireEvent.click(screen.getByText('tap')); |
| 106 | + expect(mutate).toHaveBeenCalledWith({ id: 1 }, expect.anything()); |
| 107 | + expect(loadOutbox()).toHaveLength(0); |
| 108 | + }); |
| 109 | + |
| 110 | + it('queues the tap while offline', () => { |
| 111 | + statusState.status = 'offline'; |
| 112 | + const mutate = vi.fn(); |
| 113 | + mockCheckIn.mockReturnValue({ mutate, mutateAsync: vi.fn(), isPending: false }); |
| 114 | + renderHarness(); |
| 115 | + fireEvent.click(screen.getByText('tap')); |
| 116 | + expect(mutate).not.toHaveBeenCalled(); |
| 117 | + expect(screen.getByTestId('queued')).toHaveTextContent('1'); |
| 118 | + expect(loadOutbox()).toHaveLength(1); |
| 119 | + expect(loadOutbox()[0].session_id).toBe(1); |
| 120 | + }); |
| 121 | + |
| 122 | + it('queues when the send fails without a status', () => { |
| 123 | + const mutate = vi.fn((_vars: unknown, opts?: { onError?: (e: unknown) => void }) => { |
| 124 | + opts?.onError?.(new TypeError('fetch failed')); |
| 125 | + }); |
| 126 | + mockCheckIn.mockReturnValue({ mutate, mutateAsync: vi.fn(), isPending: false }); |
| 127 | + renderHarness(); |
| 128 | + fireEvent.click(screen.getByText('tap')); |
| 129 | + expect(screen.getByTestId('queued')).toHaveTextContent('1'); |
| 130 | + expect(loadOutbox()).toHaveLength(1); |
| 131 | + }); |
| 132 | + |
| 133 | + it('does not queue HTTP errors', () => { |
| 134 | + const apiError = Object.assign(new Error('HTTP 409'), { name: 'ApiError', status: 409 }); |
| 135 | + const mutate = vi.fn((_vars: unknown, opts?: { onError?: (e: unknown) => void }) => { |
| 136 | + opts?.onError?.(apiError); |
| 137 | + }); |
| 138 | + mockCheckIn.mockReturnValue({ mutate, mutateAsync: vi.fn(), isPending: false }); |
| 139 | + renderHarness(); |
| 140 | + fireEvent.click(screen.getByText('tap')); |
| 141 | + expect(screen.getByTestId('queued')).toHaveTextContent('0'); |
| 142 | + expect(loadOutbox()).toHaveLength(0); |
| 143 | + }); |
| 144 | + |
| 145 | + it('flushes the queue with original instants on reconnect', async () => { |
| 146 | + statusState.status = 'offline'; |
| 147 | + const mutateAsync = vi.fn().mockResolvedValue({ id: 9, session_id: 1 }); |
| 148 | + mockCheckIn.mockReturnValue({ mutate: vi.fn(), mutateAsync, isPending: false }); |
| 149 | + renderHarness(); |
| 150 | + fireEvent.click(screen.getByText('tap')); |
| 151 | + // A second tap in the same millisecond dedupes honestly, so seed |
| 152 | + // the second entry directly with a distinct instant. |
| 153 | + enqueueCheckIn({ session_id: 1, recorded_at: '2026-09-14T10:01:00.000Z' }); |
| 154 | + const stamped = loadOutbox().map((e) => e.recorded_at); |
| 155 | + expect(loadOutbox()).toHaveLength(2); |
| 156 | + await act(async () => { |
| 157 | + setStatus('online'); |
| 158 | + }); |
| 159 | + await waitFor(() => expect(mutateAsync).toHaveBeenCalledTimes(2)); |
| 160 | + expect(mutateAsync).toHaveBeenNthCalledWith(1, { id: 1, recorded_at: stamped[0] }); |
| 161 | + expect(mutateAsync).toHaveBeenNthCalledWith(2, { id: 1, recorded_at: stamped[1] }); |
| 162 | + await waitFor(() => expect(loadOutbox()).toHaveLength(0)); |
| 163 | + expect(screen.getByTestId('queued')).toHaveTextContent('0'); |
| 164 | + }); |
| 165 | + |
| 166 | + it('stops the flush at the first failure', async () => { |
| 167 | + statusState.status = 'offline'; |
| 168 | + const mutateAsync = vi |
| 169 | + .fn() |
| 170 | + .mockResolvedValueOnce({ id: 9, session_id: 1 }) |
| 171 | + .mockRejectedValueOnce(new TypeError('fetch failed')); |
| 172 | + mockCheckIn.mockReturnValue({ mutate: vi.fn(), mutateAsync, isPending: false }); |
| 173 | + renderHarness(); |
| 174 | + fireEvent.click(screen.getByText('tap')); |
| 175 | + enqueueCheckIn({ session_id: 1, recorded_at: '2026-09-14T10:01:00.000Z' }); |
| 176 | + await act(async () => { |
| 177 | + setStatus('online'); |
| 178 | + }); |
| 179 | + await waitFor(() => expect(mutateAsync).toHaveBeenCalledTimes(2)); |
| 180 | + expect(loadOutbox()).toHaveLength(1); |
| 181 | + expect(screen.getByTestId('queued')).toHaveTextContent('1'); |
| 182 | + }); |
| 183 | +}); |
0 commit comments