test(pages): cover the page hooks, stores and the api client

This commit is contained in:
Maurice
2026-07-29 09:44:02 +02:00
committed by Maurice
parent bbb0f93af2
commit 1e66bcc701
90 changed files with 24168 additions and 13 deletions
+462
View File
@@ -0,0 +1,462 @@
// FE-APIWIRE-001 to FE-APIWIRE-035
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { AxiosError, type AxiosAdapter, type AxiosResponse, type InternalAxiosRequestConfig } from 'axios'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { weatherResultSchema } from '@trek/shared'
// client.ts probes the health endpoint to tell an edge-proxy auth wall apart
// from a plain offline boot — the probe result decides whether it tears down
// the service worker, so the tests drive it directly.
const { probeNow } = vi.hoisted(() => ({
probeNow: vi.fn(async (): Promise<'online' | 'offline' | 'proxy-wall'> => 'offline'),
}))
vi.mock('../sync/connectivity', () => ({ probeNow }))
const { apiClient, adminApi, mapsApi, pluginsApi, parseInDev } = await import('./client')
interface FakeLocation {
href: string
origin: string
pathname: string
search: string
hash: string
reload: () => void
}
let reload: ReturnType<typeof vi.fn<() => void>>
function setLocation(pathname: string, search = '', hash = ''): FakeLocation {
reload = vi.fn<() => void>()
const loc: FakeLocation = {
href: `http://localhost:3000${pathname}${search}${hash}`,
origin: 'http://localhost:3000',
pathname,
search,
hash,
reload,
}
Object.defineProperty(window, 'location', { writable: true, configurable: true, value: loc })
return loc
}
const realLocation = window.location
/** Records the outgoing config and answers 200 without touching the network. */
function okAdapter(sink: InternalAxiosRequestConfig[]): AxiosAdapter {
return (config) => {
sink.push(config)
return Promise.resolve({
data: { ok: true }, status: 200, statusText: 'OK', headers: {}, config,
} as AxiosResponse)
}
}
/** Rejects the way a CORS/offline failure does: an error with no `response`. */
const networkErrorAdapter: AxiosAdapter = (config) =>
Promise.reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config))
async function captureError(run: () => Promise<unknown>): Promise<AxiosError> {
const err = await run().then(() => null, (e: unknown) => e as AxiosError)
expect(err, 'expected the request to reject').not.toBeNull()
return err as AxiosError
}
beforeEach(() => {
probeNow.mockResolvedValue('offline')
setLocation('/dashboard')
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
Object.defineProperty(window, 'location', { writable: true, configurable: true, value: realLocation })
delete (navigator as { serviceWorker?: unknown }).serviceWorker
})
describe('client > request interceptor', () => {
it('FE-APIWIRE-001: mutating requests get an idempotency key, reads do not', async () => {
const sink: InternalAxiosRequestConfig[] = []
const adapter = okAdapter(sink)
await apiClient.get('/probe', { adapter })
await apiClient.post('/probe', {}, { adapter })
await apiClient.put('/probe', {}, { adapter })
await apiClient.patch('/probe', {}, { adapter })
await apiClient.delete('/probe', { adapter })
const keys = sink.map(c => c.headers['X-Idempotency-Key'])
expect(keys[0]).toBeUndefined()
for (const key of keys.slice(1)) expect(typeof key).toBe('string')
})
it('FE-APIWIRE-002: each write gets its own key so retries can be deduplicated', async () => {
const sink: InternalAxiosRequestConfig[] = []
const adapter = okAdapter(sink)
await apiClient.post('/probe', {}, { adapter })
await apiClient.post('/probe', {}, { adapter })
expect(sink[0].headers['X-Idempotency-Key']).not.toBe(sink[1].headers['X-Idempotency-Key'])
})
it('FE-APIWIRE-003: a pre-generated key from the mutation queue is left alone', async () => {
const sink: InternalAxiosRequestConfig[] = []
await apiClient.post('/probe', {}, {
adapter: okAdapter(sink),
headers: { 'X-Idempotency-Key': 'queued-key' },
})
expect(sink[0].headers['X-Idempotency-Key']).toBe('queued-key')
})
it('FE-APIWIRE-004: falls back to a random token when crypto.randomUUID is missing', async () => {
const realCrypto = globalThis.crypto
vi.stubGlobal('crypto', {
getRandomValues: realCrypto.getRandomValues.bind(realCrypto),
} as unknown as Crypto)
const sink: InternalAxiosRequestConfig[] = []
await apiClient.post('/probe', {}, { adapter: okAdapter(sink) })
const key = String(sink[0].headers['X-Idempotency-Key'])
expect(key).toMatch(/^[a-z0-9]+$/)
expect(key).not.toMatch(/-/)
})
it('FE-APIWIRE-005: the socket id header is omitted while no socket is connected', async () => {
const sink: InternalAxiosRequestConfig[] = []
await apiClient.get('/probe', { adapter: okAdapter(sink) })
expect(sink[0].headers['X-Socket-Id']).toBeUndefined()
})
it('FE-APIWIRE-034: a rejection from an earlier request interceptor is passed on untouched', async () => {
const boom = new Error('interceptor refused the request')
const id = apiClient.interceptors.request.use(() => Promise.reject(boom))
const sink: InternalAxiosRequestConfig[] = []
try {
await expect(apiClient.post('/probe', {}, { adapter: okAdapter(sink) })).rejects.toBe(boom)
} finally {
apiClient.interceptors.request.eject(id)
}
expect(sink).toHaveLength(0)
})
})
describe('client > rate-limit translation', () => {
beforeEach(() => {
server.use(http.get('/api/limited', () => HttpResponse.json({ error: 'Too Many Requests' }, { status: 429 })))
})
it('FE-APIWIRE-006: a 429 is rewritten in the stored app language', async () => {
localStorage.setItem('app_language', 'de')
const err = await captureError(() => apiClient.get('/limited'))
expect(err.message).toBe('Zu viele Versuche. Bitte versuchen Sie es später erneut.')
expect((err.response?.data as { error: string }).error)
.toBe('Zu viele Versuche. Bitte versuchen Sie es später erneut.')
})
it('FE-APIWIRE-007: an unsupported language falls back to English', async () => {
localStorage.setItem('app_language', 'kl')
const err = await captureError(() => apiClient.get('/limited'))
expect(err.message).toBe('Too many attempts. Please try again later.')
})
it('FE-APIWIRE-008: no stored language falls back to English', async () => {
const err = await captureError(() => apiClient.get('/limited'))
expect(err.message).toBe('Too many attempts. Please try again later.')
})
it('FE-APIWIRE-009: a blocked localStorage still yields the English message', async () => {
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new Error('storage disabled')
})
const err = await captureError(() => apiClient.get('/limited'))
expect(err.message).toBe('Too many attempts. Please try again later.')
})
it('FE-APIWIRE-010: a non-object 429 body is replaced with the translated error object', async () => {
server.use(http.get('/api/limited', () => new HttpResponse('slow down', { status: 429 })))
const err = await captureError(() => apiClient.get('/limited'))
expect(err.response?.data).toEqual({ error: 'Too many attempts. Please try again later.' })
})
})
describe('client > proxy auth challenges', () => {
function installServiceWorker(unregister: () => Promise<boolean>) {
const getRegistration = vi.fn(async () => ({ unregister }))
Object.defineProperty(navigator, 'serviceWorker', {
writable: true, configurable: true, value: { getRegistration },
})
return getRegistration
}
it('FE-APIWIRE-011: an HTML 401 unregisters the service worker and reloads', async () => {
const unregister = vi.fn(async () => true)
installServiceWorker(unregister)
server.use(http.get('/api/auth/me', () =>
new HttpResponse('<html>login</html>', { status: 401, headers: { 'Content-Type': 'text/html' } })))
await captureError(() => apiClient.get('/auth/me'))
expect(unregister).toHaveBeenCalled()
expect(reload).toHaveBeenCalledTimes(1)
expect(sessionStorage.getItem('proxy_reauth_attempted')).toBe('1')
})
it('FE-APIWIRE-012: the reauth reload only fires once per session', async () => {
installServiceWorker(vi.fn(async () => true))
sessionStorage.setItem('proxy_reauth_attempted', '1')
server.use(http.get('/api/auth/me', () =>
new HttpResponse('<html>login</html>', { status: 401, headers: { 'Content-Type': 'text/html' } })))
await captureError(() => apiClient.get('/auth/me'))
expect(reload).not.toHaveBeenCalled()
})
it('FE-APIWIRE-013: an HTML 401 on a public path never reloads', async () => {
setLocation('/login')
server.use(http.get('/api/auth/me', () =>
new HttpResponse('<html>login</html>', { status: 401, headers: { 'Content-Type': 'text/html' } })))
await captureError(() => apiClient.get('/auth/me'))
expect(reload).not.toHaveBeenCalled()
expect(sessionStorage.getItem('proxy_reauth_attempted')).toBeNull()
})
it('FE-APIWIRE-014: a response-less failure that probes proxy-wall reloads', async () => {
probeNow.mockResolvedValue('proxy-wall')
installServiceWorker(vi.fn(async () => true))
await captureError(() => apiClient.get('/auth/me', { adapter: networkErrorAdapter }))
expect(probeNow).toHaveBeenCalled()
expect(reload).toHaveBeenCalledTimes(1)
})
it('FE-APIWIRE-015: a response-less failure that probes offline keeps the SW (#1346)', async () => {
probeNow.mockResolvedValue('offline')
const getRegistration = installServiceWorker(vi.fn(async () => true))
await captureError(() => apiClient.get('/auth/me', { adapter: networkErrorAdapter }))
expect(getRegistration).not.toHaveBeenCalled()
expect(reload).not.toHaveBeenCalled()
expect(sessionStorage.getItem('proxy_reauth_attempted')).toBeNull()
})
it('FE-APIWIRE-016: a failing unregister still reloads into the proxy challenge', async () => {
probeNow.mockResolvedValue('proxy-wall')
Object.defineProperty(navigator, 'serviceWorker', {
writable: true, configurable: true,
value: { getRegistration: vi.fn(async () => { throw new Error('SW gone') }) },
})
await captureError(() => apiClient.get('/auth/me', { adapter: networkErrorAdapter }))
expect(reload).toHaveBeenCalledTimes(1)
})
it('FE-APIWIRE-017: a proxy-wall probe on a shared page does not reload', async () => {
setLocation('/shared/tok123')
probeNow.mockResolvedValue('proxy-wall')
await captureError(() => apiClient.get('/auth/me', { adapter: networkErrorAdapter }))
expect(reload).not.toHaveBeenCalled()
})
it('FE-APIWIRE-035: a 401 without a content-type is not mistaken for a proxy login page', async () => {
installServiceWorker(vi.fn(async () => true))
server.use(http.get('/api/auth/me', () => new HttpResponse(null, { status: 401 })))
await captureError(() => apiClient.get('/auth/me'))
expect(reload).not.toHaveBeenCalled()
expect(sessionStorage.getItem('proxy_reauth_attempted')).toBeNull()
})
it('FE-APIWIRE-018: a successful response clears the reauth marker', async () => {
sessionStorage.setItem('proxy_reauth_attempted', '1')
server.use(http.get('/api/auth/me', () => HttpResponse.json({ ok: true })))
await apiClient.get('/auth/me')
expect(sessionStorage.getItem('proxy_reauth_attempted')).toBeNull()
})
})
describe('client > redirect handling', () => {
it('FE-APIWIRE-019: a JSON AUTH_REQUIRED 401 redirects with the full current path', async () => {
const loc = setLocation('/trips/7', '?tab=map', '#day-2')
server.use(http.get('/api/auth/me', () => HttpResponse.json({ code: 'AUTH_REQUIRED' }, { status: 401 })))
await captureError(() => apiClient.get('/auth/me'))
expect(loc.href).toBe('/login?redirect=' + encodeURIComponent('/trips/7?tab=map#day-2'))
})
it('FE-APIWIRE-020: an MFA_REQUIRED 403 sends the user to the settings page', async () => {
const loc = setLocation('/dashboard')
server.use(http.get('/api/auth/me', () => HttpResponse.json({ code: 'MFA_REQUIRED' }, { status: 403 })))
await captureError(() => apiClient.get('/auth/me'))
expect(loc.href).toBe('/settings?mfa=required')
})
})
describe('client > dev-only contract drift checks', () => {
it('FE-APIWIRE-021: parseInDev passes a matching payload straight through', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const payload = { temp: 21, main: 'Clear', description: 'clear sky', type: 'sun' }
expect(parseInDev(weatherResultSchema, payload, 'weather.get')).toBe(payload)
expect(warn).not.toHaveBeenCalled()
})
it('FE-APIWIRE-022: parseInDev warns but still returns a drifting payload', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const payload = { temp: 'warm', main: 'Clear', description: 'clear sky', type: 'sun' }
expect(parseInDev(weatherResultSchema, payload, 'weather.get')).toBe(payload)
expect(warn).toHaveBeenCalledWith(
'[api] weather.get: response did not match the @trek/shared schema',
expect.anything(),
)
})
it('FE-APIWIRE-023: a drifting maps response is reported under its own label', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
server.use(http.post('/api/maps/search', () => HttpResponse.json({ nonsense: true })))
await expect(mapsApi.search('Rome')).resolves.toEqual({ nonsense: true })
expect(warn).toHaveBeenCalledWith(
'[api] maps.search: response did not match the @trek/shared schema',
expect.anything(),
)
})
})
describe('client > pluginsApi.invoke namespace guard', () => {
it('FE-APIWIRE-024: a relative sub-path stays inside the plugin namespace', async () => {
let seen = ''
server.use(http.get('/api/plugins/koffi/ping', ({ request }) => {
seen = new URL(request.url).pathname
return HttpResponse.json({ pong: true })
}))
await expect(pluginsApi.invoke('koffi', '/ping')).resolves.toEqual({ pong: true })
expect(seen).toBe('/api/plugins/koffi/ping')
})
it('FE-APIWIRE-025: method, body and query string survive the rewrite', async () => {
let received: unknown
let query = ''
server.use(http.post('/api/plugins/koffi/sync', async ({ request }) => {
received = await request.json()
query = new URL(request.url).search
return HttpResponse.json({ ok: true })
}))
await pluginsApi.invoke('koffi', 'sync?full=1', { method: 'POST', body: { since: 5 } })
expect(received).toEqual({ since: 5 })
expect(query).toBe('?full=1')
})
it('FE-APIWIRE-026: traversal out of the plugin prefix is refused', async () => {
await expect(pluginsApi.invoke('koffi', '/../../auth/me'))
.rejects.toThrow('plugin route escapes its namespace')
})
it('FE-APIWIRE-027: an absolute off-origin target is refused', async () => {
await expect(pluginsApi.invoke('koffi', 'https://evil.test/steal'))
.rejects.toThrow('plugin route escapes its namespace')
})
it('FE-APIWIRE-028: an unparseable sub-path is refused before any request', async () => {
await expect(pluginsApi.invoke('koffi', 'http://')).rejects.toThrow('invalid plugin route')
})
})
describe('client > adminApi.llmLocalPull', () => {
function streamingResponse(chunks: string[]): Response {
let i = 0
const encoder = new TextEncoder()
return {
ok: true,
status: 200,
body: {
getReader: () => ({
read: async () => (i < chunks.length
? { done: false, value: encoder.encode(chunks[i++]) }
: { done: true, value: undefined }),
}),
},
} as unknown as Response
}
it('FE-APIWIRE-029: NDJSON progress lines are reported even when split across chunks', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(streamingResponse([
'{"status":"pulling","total":100,"completed":10}\n{"status":"pul',
'ling","total":100,"completed":90}\n{"status":"success"}\n',
]))
const onProgress = vi.fn((_p: { status?: string }) => {})
await adminApi.llmLocalPull('http://ollama:11434', 'qwen3:8b', onProgress)
expect(onProgress.mock.calls.map(c => c[0])).toEqual([
{ status: 'pulling', total: 100, completed: 10 },
{ status: 'pulling', total: 100, completed: 90 },
{ status: 'success' },
])
})
it('FE-APIWIRE-030: blank and half-written lines are skipped instead of throwing', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(streamingResponse([
'\n \n{"status":"a"}\nnot-json\n{"status":"b"}\n',
]))
const onProgress = vi.fn((_p: { status?: string }) => {})
await adminApi.llmLocalPull('http://ollama:11434', 'qwen3:8b', onProgress)
expect(onProgress.mock.calls.map(c => c[0])).toEqual([{ status: 'a' }, { status: 'b' }])
})
it('FE-APIWIRE-031: a JSON error body becomes the thrown message', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce({
ok: false, status: 502, body: null,
json: async () => ({ error: 'ollama unreachable' }),
} as unknown as Response)
await expect(adminApi.llmLocalPull('http://ollama:11434', 'x', vi.fn()))
.rejects.toThrow('ollama unreachable')
})
it('FE-APIWIRE-032: a non-JSON error body falls back to the status code', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce({
ok: false, status: 500, body: null,
json: async () => { throw new SyntaxError('not json') },
} as unknown as Response)
await expect(adminApi.llmLocalPull('http://ollama:11434', 'x', vi.fn()))
.rejects.toThrow('Pull failed (500)')
})
it('FE-APIWIRE-033: a 200 without a readable body is treated as a failure', async () => {
vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce({
ok: true, status: 200, body: null,
json: async () => ({}),
} as unknown as Response)
await expect(adminApi.llmLocalPull('http://ollama:11434', 'x', vi.fn()))
.rejects.toThrow('Pull failed (200)')
})
})
+843
View File
@@ -0,0 +1,843 @@
// FE-APISURF-001 to FE-APISURF-052
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import type { AxiosResponse } from 'axios'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import {
apiClient,
authApi, oauthApi, tripsApi, daysApi, placesApi, assignmentsApi, packingApi, todoApi,
tagsApi, categoriesApi, adminApi, addonsApi, pluginsApi, airtrailApi, journeyApi,
mapsApi, airportsApi, budgetApi, filesApi, reservationsApi, healthApi, weatherApi,
configApi, helpApi, settingsApi, accommodationsApi, dayNotesApi, collabApi, backupApi,
shareApi, transitApi, tripInviteApi, notificationsApi, inAppNotificationsApi,
} from './client'
interface Recorded { method: string; url: string; body: unknown }
let log: Recorded[] = []
/** One record per outgoing request: verb, path+query and (parsed) JSON body. */
function recorder() {
return http.all(/\/api\//, async ({ request }) => {
const url = new URL(request.url)
const raw = await request.text()
let body: unknown
if (raw) {
try { body = JSON.parse(raw) } catch { body = raw }
}
log.push({ method: request.method, url: url.pathname + url.search, body })
return HttpResponse.json({ ok: true })
})
}
beforeEach(() => {
log = []
server.use(recorder())
// parseInDev/checkInDev warn on every stub payload that doesn't match its
// @trek/shared schema — expected here, so keep the output readable.
vi.spyOn(console, 'warn').mockImplementation(() => {})
})
afterEach(() => {
vi.restoreAllMocks()
})
interface Call { n: string; r: () => Promise<unknown>; e: string }
/** Runs every call in isolation and checks the verb + path it produced. */
async function assertCalls(calls: Call[]): Promise<void> {
for (const c of calls) {
log = []
await c.r()
expect(log.length, `${c.n}: expected exactly one request`).toBe(1)
const rec = log[0]
const [path] = rec.url.split('?')
expect(`${rec.method} ${path}`, c.n).toBe(c.e)
}
}
/** Runs one call and returns the request it produced. */
async function traceOne(run: () => Promise<unknown>): Promise<Recorded> {
log = []
await run()
expect(log).toHaveLength(1)
return log[0]
}
describe('client > endpoint wiring', () => {
it('FE-APISURF-001: authApi maps every method to its auth endpoint', async () => {
await assertCalls([
{ n: 'register', r: () => authApi.register({ email: 'a@b.c', password: 'pw' }), e: 'POST /api/auth/register' },
{ n: 'validateInvite', r: () => authApi.validateInvite('inv-tok'), e: 'GET /api/auth/invite/inv-tok' },
{ n: 'login', r: () => authApi.login({ email: 'a@b.c', password: 'pw' }), e: 'POST /api/auth/login' },
{ n: 'verifyMfaLogin', r: () => authApi.verifyMfaLogin({ mfa_token: 'm', code: '123456' }), e: 'POST /api/auth/mfa/verify-login' },
{ n: 'mfaSetup', r: () => authApi.mfaSetup(), e: 'POST /api/auth/mfa/setup' },
{ n: 'mfaEnable', r: () => authApi.mfaEnable({ code: '123456' }), e: 'POST /api/auth/mfa/enable' },
{ n: 'mfaDisable', r: () => authApi.mfaDisable({ password: 'pw', code: '123456' }), e: 'POST /api/auth/mfa/disable' },
{ n: 'me', r: () => authApi.me(), e: 'GET /api/auth/me' },
{ n: 'updateMapsKey', r: () => authApi.updateMapsKey('gkey'), e: 'PUT /api/auth/me/maps-key' },
{ n: 'updateApiKeys', r: () => authApi.updateApiKeys({ google_maps: null }), e: 'PUT /api/auth/me/api-keys' },
{ n: 'updateSettings', r: () => authApi.updateSettings({ theme: 'dark' }), e: 'PUT /api/auth/me/settings' },
{ n: 'getSettings', r: () => authApi.getSettings(), e: 'GET /api/auth/me/settings' },
{ n: 'listUsers', r: () => authApi.listUsers(), e: 'GET /api/auth/users' },
{ n: 'deleteAvatar', r: () => authApi.deleteAvatar(), e: 'DELETE /api/auth/avatar' },
{ n: 'getAppConfig', r: () => authApi.getAppConfig(), e: 'GET /api/auth/app-config' },
{ n: 'updateAppSettings', r: () => authApi.updateAppSettings({ registration_enabled: true }), e: 'PUT /api/auth/app-settings' },
{ n: 'validateKeys', r: () => authApi.validateKeys(), e: 'GET /api/auth/validate-keys' },
{ n: 'travelStats', r: () => authApi.travelStats(), e: 'GET /api/auth/travel-stats' },
{ n: 'changePassword', r: () => authApi.changePassword({ current_password: 'a', new_password: 'b' }), e: 'PUT /api/auth/me/password' },
{ n: 'forgotPassword', r: () => authApi.forgotPassword({ email: 'a@b.c' }), e: 'POST /api/auth/forgot-password' },
{ n: 'resetPassword', r: () => authApi.resetPassword({ token: 't', new_password: 'b' }), e: 'POST /api/auth/reset-password' },
{ n: 'deleteOwnAccount', r: () => authApi.deleteOwnAccount(), e: 'DELETE /api/auth/me' },
{ n: 'demoLogin', r: () => authApi.demoLogin(), e: 'POST /api/auth/demo-login' },
{ n: 'mcpTokens.list', r: () => authApi.mcpTokens.list(), e: 'GET /api/auth/mcp-tokens' },
{ n: 'mcpTokens.create', r: () => authApi.mcpTokens.create('cli'), e: 'POST /api/auth/mcp-tokens' },
{ n: 'mcpTokens.delete', r: () => authApi.mcpTokens.delete(7), e: 'DELETE /api/auth/mcp-tokens/7' },
{ n: 'passkey.registerOptions', r: () => authApi.passkey.registerOptions('pw'), e: 'POST /api/auth/passkey/register/options' },
{ n: 'passkey.registerVerify', r: () => authApi.passkey.registerVerify({ id: 'cred' }, 'Yubikey'), e: 'POST /api/auth/passkey/register/verify' },
{ n: 'passkey.loginOptions', r: () => authApi.passkey.loginOptions(), e: 'POST /api/auth/passkey/login/options' },
{ n: 'passkey.loginVerify', r: () => authApi.passkey.loginVerify({ id: 'cred' }), e: 'POST /api/auth/passkey/login/verify' },
{ n: 'passkey.list', r: () => authApi.passkey.list(), e: 'GET /api/auth/passkey/credentials' },
{ n: 'passkey.rename', r: () => authApi.passkey.rename(3, 'Phone'), e: 'PATCH /api/auth/passkey/credentials/3' },
{ n: 'passkey.delete', r: () => authApi.passkey.delete(3, 'pw'), e: 'DELETE /api/auth/passkey/credentials/3' },
])
})
it('FE-APISURF-002: oauthApi maps consent + client/session management endpoints', async () => {
const params = {
response_type: 'code', client_id: 'cid', redirect_uri: 'https://app/cb',
scope: 'trips:read', code_challenge: 'chal', code_challenge_method: 'S256',
}
await assertCalls([
{ n: 'validate', r: () => oauthApi.validate(params), e: 'GET /api/oauth/authorize/validate' },
{ n: 'authorize', r: () => oauthApi.authorize({ ...params, approved: true }), e: 'POST /api/oauth/authorize' },
{ n: 'clients.list', r: () => oauthApi.clients.list(), e: 'GET /api/oauth/clients' },
{ n: 'clients.create', r: () => oauthApi.clients.create({ name: 'App', allowed_scopes: ['trips:read'] }), e: 'POST /api/oauth/clients' },
{ n: 'clients.rotate', r: () => oauthApi.clients.rotate('cid'), e: 'POST /api/oauth/clients/cid/rotate' },
{ n: 'clients.delete', r: () => oauthApi.clients.delete('cid'), e: 'DELETE /api/oauth/clients/cid' },
{ n: 'sessions.list', r: () => oauthApi.sessions.list(), e: 'GET /api/oauth/sessions' },
{ n: 'sessions.revoke', r: () => oauthApi.sessions.revoke(4), e: 'DELETE /api/oauth/sessions/4' },
])
})
it('FE-APISURF-003: tripsApi maps trip, member and guest endpoints', async () => {
await assertCalls([
{ n: 'list', r: () => tripsApi.list(), e: 'GET /api/trips' },
{ n: 'create', r: () => tripsApi.create({ title: 'Rome' }), e: 'POST /api/trips' },
{ n: 'get', r: () => tripsApi.get(3), e: 'GET /api/trips/3' },
{ n: 'update', r: () => tripsApi.update(3, { title: 'Rome 2' }), e: 'PUT /api/trips/3' },
{ n: 'delete', r: () => tripsApi.delete(3), e: 'DELETE /api/trips/3' },
{ n: 'searchCoverImages', r: () => tripsApi.searchCoverImages('rome'), e: 'GET /api/trips/cover-images/search' },
{ n: 'archive', r: () => tripsApi.archive(3), e: 'PUT /api/trips/3' },
{ n: 'unarchive', r: () => tripsApi.unarchive(3), e: 'PUT /api/trips/3' },
{ n: 'getMembers', r: () => tripsApi.getMembers(3), e: 'GET /api/trips/3/members' },
{ n: 'addMember', r: () => tripsApi.addMember(3, 'bob'), e: 'POST /api/trips/3/members' },
{ n: 'removeMember', r: () => tripsApi.removeMember(3, 9), e: 'DELETE /api/trips/3/members/9' },
{ n: 'transferOwnership', r: () => tripsApi.transferOwnership(3, 9), e: 'POST /api/trips/3/transfer' },
{ n: 'createGuest', r: () => tripsApi.createGuest(3, 'Anna'), e: 'POST /api/trips/3/guests' },
{ n: 'renameGuest', r: () => tripsApi.renameGuest(3, 9, 'Ana'), e: 'PUT /api/trips/3/guests/9' },
{ n: 'deleteGuest', r: () => tripsApi.deleteGuest(3, 9), e: 'DELETE /api/trips/3/guests/9' },
{ n: 'copy', r: () => tripsApi.copy(3, { title: 'Copy' }), e: 'POST /api/trips/3/copy' },
{ n: 'bundle', r: () => tripsApi.bundle(3), e: 'GET /api/trips/3/bundle' },
])
})
it('FE-APISURF-004: daysApi and dayNotesApi map their nested trip endpoints', async () => {
await assertCalls([
{ n: 'days.list', r: () => daysApi.list(1), e: 'GET /api/trips/1/days' },
{ n: 'days.create', r: () => daysApi.create(1, { date: '2026-06-01' }), e: 'POST /api/trips/1/days' },
{ n: 'days.update', r: () => daysApi.update(1, 2, { notes: 'hi' }), e: 'PUT /api/trips/1/days/2' },
{ n: 'days.updateTransport', r: () => daysApi.updateTransport(1, 2, 'car'), e: 'PUT /api/trips/1/days/2/transport' },
{ n: 'days.delete', r: () => daysApi.delete(1, 2), e: 'DELETE /api/trips/1/days/2' },
{ n: 'days.reorder', r: () => daysApi.reorder(1, [2, 1]), e: 'PUT /api/trips/1/days/reorder' },
{ n: 'dayNotes.list', r: () => dayNotesApi.list(1, 2), e: 'GET /api/trips/1/days/2/notes' },
{ n: 'dayNotes.create', r: () => dayNotesApi.create(1, 2, { text: 'note' }), e: 'POST /api/trips/1/days/2/notes' },
{ n: 'dayNotes.update', r: () => dayNotesApi.update(1, 2, 5, { text: 'edit' }), e: 'PUT /api/trips/1/days/2/notes/5' },
{ n: 'dayNotes.delete', r: () => dayNotesApi.delete(1, 2, 5), e: 'DELETE /api/trips/1/days/2/notes/5' },
])
})
it('FE-APISURF-005: placesApi maps CRUD, rating and list-import endpoints', async () => {
await assertCalls([
{ n: 'list', r: () => placesApi.list(1), e: 'GET /api/trips/1/places' },
{ n: 'create', r: () => placesApi.create(1, { name: 'Colosseum' }), e: 'POST /api/trips/1/places' },
{ n: 'get', r: () => placesApi.get(1, 5), e: 'GET /api/trips/1/places/5' },
{ n: 'update', r: () => placesApi.update(1, 5, { name: 'Forum' }), e: 'PUT /api/trips/1/places/5' },
{ n: 'delete', r: () => placesApi.delete(1, 5), e: 'DELETE /api/trips/1/places/5' },
{ n: 'searchImage', r: () => placesApi.searchImage(1, 5), e: 'GET /api/trips/1/places/5/image' },
{ n: 'importGoogleList', r: () => placesApi.importGoogleList(1, 'https://maps.app/x'), e: 'POST /api/trips/1/places/import/google-list' },
{ n: 'importNaverList', r: () => placesApi.importNaverList(1, 'https://naver/x'), e: 'POST /api/trips/1/places/import/naver-list' },
{ n: 'bulkDelete', r: () => placesApi.bulkDelete(1, [5, 6]), e: 'POST /api/trips/1/places/bulk-delete' },
{ n: 'bulkUpdate', r: () => placesApi.bulkUpdate(1, [5], { category_id: 2 }), e: 'POST /api/trips/1/places/bulk-update' },
])
})
it('FE-APISURF-006: assignmentsApi maps day-plan endpoints', async () => {
await assertCalls([
{ n: 'list', r: () => assignmentsApi.list(1, 2), e: 'GET /api/trips/1/days/2/assignments' },
{ n: 'create', r: () => assignmentsApi.create(1, 2, { place_id: 5 }), e: 'POST /api/trips/1/days/2/assignments' },
{ n: 'delete', r: () => assignmentsApi.delete(1, 2, 7), e: 'DELETE /api/trips/1/days/2/assignments/7' },
{ n: 'reorder', r: () => assignmentsApi.reorder(1, 2, [7, 8]), e: 'PUT /api/trips/1/days/2/assignments/reorder' },
{ n: 'move', r: () => assignmentsApi.move(1, 7, 3, 0), e: 'PUT /api/trips/1/assignments/7/move' },
{ n: 'update', r: () => assignmentsApi.update(1, 2, 7, { notes: 'x' }), e: 'PUT /api/trips/1/days/2/assignments/7' },
{ n: 'getParticipants', r: () => assignmentsApi.getParticipants(1, 7), e: 'GET /api/trips/1/assignments/7/participants' },
{ n: 'setParticipants', r: () => assignmentsApi.setParticipants(1, 7, [4]), e: 'PUT /api/trips/1/assignments/7/participants' },
{ n: 'updateTime', r: () => assignmentsApi.updateTime(1, 7, { place_time: '09:00' }), e: 'PUT /api/trips/1/assignments/7/time' },
{ n: 'updateTransport', r: () => assignmentsApi.updateTransport(1, 7, null), e: 'PUT /api/trips/1/assignments/7/transport' },
])
})
it('FE-APISURF-007: packingApi maps item, bag and template endpoints', async () => {
await assertCalls([
{ n: 'list', r: () => packingApi.list(1), e: 'GET /api/trips/1/packing' },
{ n: 'create', r: () => packingApi.create(1, { name: 'Towel' }), e: 'POST /api/trips/1/packing' },
{ n: 'bulkImport', r: () => packingApi.bulkImport(1, [{ name: 'Socks' }]), e: 'POST /api/trips/1/packing/import' },
{ n: 'update', r: () => packingApi.update(1, 4, { checked: true }), e: 'PUT /api/trips/1/packing/4' },
{ n: 'delete', r: () => packingApi.delete(1, 4), e: 'DELETE /api/trips/1/packing/4' },
{ n: 'reorder', r: () => packingApi.reorder(1, [4, 5]), e: 'PUT /api/trips/1/packing/reorder' },
{ n: 'setSharing', r: () => packingApi.setSharing(1, 4, { visibility: 'shared' }), e: 'PUT /api/trips/1/packing/4/sharing' },
{ n: 'clone', r: () => packingApi.clone(1, 4), e: 'POST /api/trips/1/packing/4/clone' },
{ n: 'addContributor', r: () => packingApi.addContributor(1, 4), e: 'POST /api/trips/1/packing/4/contributors' },
{ n: 'removeContributor', r: () => packingApi.removeContributor(1, 4, 9), e: 'DELETE /api/trips/1/packing/4/contributors/9' },
{ n: 'getCategoryAssignees', r: () => packingApi.getCategoryAssignees(1), e: 'GET /api/trips/1/packing/category-assignees' },
{ n: 'listTemplates', r: () => packingApi.listTemplates(1), e: 'GET /api/trips/1/packing/templates' },
{ n: 'applyTemplate', r: () => packingApi.applyTemplate(1, 6), e: 'POST /api/trips/1/packing/apply-template/6' },
{ n: 'saveAsTemplate', r: () => packingApi.saveAsTemplate(1, 'Beach'), e: 'POST /api/trips/1/packing/save-as-template' },
{ n: 'setBagMembers', r: () => packingApi.setBagMembers(1, 2, [9]), e: 'PUT /api/trips/1/packing/bags/2/members' },
{ n: 'listBags', r: () => packingApi.listBags(1), e: 'GET /api/trips/1/packing/bags' },
{ n: 'createBag', r: () => packingApi.createBag(1, { name: 'Carry-on' }), e: 'POST /api/trips/1/packing/bags' },
{ n: 'updateBag', r: () => packingApi.updateBag(1, 2, { name: 'Hold' }), e: 'PUT /api/trips/1/packing/bags/2' },
{ n: 'deleteBag', r: () => packingApi.deleteBag(1, 2), e: 'DELETE /api/trips/1/packing/bags/2' },
])
})
it('FE-APISURF-008: todoApi maps todo endpoints', async () => {
await assertCalls([
{ n: 'list', r: () => todoApi.list(1), e: 'GET /api/trips/1/todo' },
{ n: 'create', r: () => todoApi.create(1, { name: 'Book train' }), e: 'POST /api/trips/1/todo' },
{ n: 'update', r: () => todoApi.update(1, 3, { checked: true }), e: 'PUT /api/trips/1/todo/3' },
{ n: 'delete', r: () => todoApi.delete(1, 3), e: 'DELETE /api/trips/1/todo/3' },
{ n: 'reorder', r: () => todoApi.reorder(1, [3, 4]), e: 'PUT /api/trips/1/todo/reorder' },
{ n: 'getCategoryAssignees', r: () => todoApi.getCategoryAssignees(1), e: 'GET /api/trips/1/todo/category-assignees' },
])
})
it('FE-APISURF-009: tagsApi and categoriesApi map their global endpoints', async () => {
await assertCalls([
{ n: 'tags.list', r: () => tagsApi.list(), e: 'GET /api/tags' },
{ n: 'tags.create', r: () => tagsApi.create({ name: 'Food' }), e: 'POST /api/tags' },
{ n: 'tags.update', r: () => tagsApi.update(2, { name: 'Eat' }), e: 'PUT /api/tags/2' },
{ n: 'tags.delete', r: () => tagsApi.delete(2), e: 'DELETE /api/tags/2' },
{ n: 'categories.list', r: () => categoriesApi.list(), e: 'GET /api/categories' },
{ n: 'categories.create', r: () => categoriesApi.create({ name: 'Museum' }), e: 'POST /api/categories' },
{ n: 'categories.update', r: () => categoriesApi.update(2, { name: 'Art' }), e: 'PUT /api/categories/2' },
{ n: 'categories.delete', r: () => categoriesApi.delete(2), e: 'DELETE /api/categories/2' },
])
})
it('FE-APISURF-010: adminApi maps user, addon and settings endpoints', async () => {
await assertCalls([
{ n: 'users', r: () => adminApi.users(), e: 'GET /api/admin/users' },
{ n: 'createUser', r: () => adminApi.createUser({ email: 'a@b.c' }), e: 'POST /api/admin/users' },
{ n: 'updateUser', r: () => adminApi.updateUser(2, { role: 'admin' }), e: 'PUT /api/admin/users/2' },
{ n: 'deleteUser', r: () => adminApi.deleteUser(2), e: 'DELETE /api/admin/users/2' },
{ n: 'resetUserPasskeys', r: () => adminApi.resetUserPasskeys(2), e: 'DELETE /api/admin/users/2/passkeys' },
{ n: 'stats', r: () => adminApi.stats(), e: 'GET /api/admin/stats' },
{ n: 'saveDemoBaseline', r: () => adminApi.saveDemoBaseline(), e: 'POST /api/admin/save-demo-baseline' },
{ n: 'getOidc', r: () => adminApi.getOidc(), e: 'GET /api/admin/oidc' },
{ n: 'updateOidc', r: () => adminApi.updateOidc({ enabled: true }), e: 'PUT /api/admin/oidc' },
{ n: 'addons', r: () => adminApi.addons(), e: 'GET /api/admin/addons' },
{ n: 'updateAddon', r: () => adminApi.updateAddon(3, { enabled: false }), e: 'PUT /api/admin/addons/3' },
{ n: 'checkVersion', r: () => adminApi.checkVersion(), e: 'GET /api/admin/version-check' },
{ n: 'getBagTracking', r: () => adminApi.getBagTracking(), e: 'GET /api/admin/bag-tracking' },
{ n: 'updateBagTracking', r: () => adminApi.updateBagTracking(true), e: 'PUT /api/admin/bag-tracking' },
{ n: 'getPlacesPhotos', r: () => adminApi.getPlacesPhotos(), e: 'GET /api/admin/places-photos' },
{ n: 'updatePlacesPhotos', r: () => adminApi.updatePlacesPhotos(false), e: 'PUT /api/admin/places-photos' },
{ n: 'getPlacesAutocomplete', r: () => adminApi.getPlacesAutocomplete(), e: 'GET /api/admin/places-autocomplete' },
{ n: 'updatePlacesAutocomplete', r: () => adminApi.updatePlacesAutocomplete(true), e: 'PUT /api/admin/places-autocomplete' },
{ n: 'getPlacesDetails', r: () => adminApi.getPlacesDetails(), e: 'GET /api/admin/places-details' },
{ n: 'updatePlacesDetails', r: () => adminApi.updatePlacesDetails(true), e: 'PUT /api/admin/places-details' },
{ n: 'getCollabFeatures', r: () => adminApi.getCollabFeatures(), e: 'GET /api/admin/collab-features' },
{ n: 'updateCollabFeatures', r: () => adminApi.updateCollabFeatures({ polls: true }), e: 'PUT /api/admin/collab-features' },
{ n: 'getPermissions', r: () => adminApi.getPermissions(), e: 'GET /api/admin/permissions' },
{ n: 'updatePermissions', r: () => adminApi.updatePermissions({ edit_trip: 'member' }), e: 'PUT /api/admin/permissions' },
{ n: 'rotateJwtSecret', r: () => adminApi.rotateJwtSecret(), e: 'POST /api/admin/rotate-jwt-secret' },
{ n: 'sendTestNotification', r: () => adminApi.sendTestNotification({ channel: 'email' }), e: 'POST /api/admin/dev/test-notification' },
{ n: 'getNotificationPreferences', r: () => adminApi.getNotificationPreferences(), e: 'GET /api/admin/notification-preferences' },
{ n: 'updateNotificationPreferences', r: () => adminApi.updateNotificationPreferences({ email: { trip_invite: true } }), e: 'PUT /api/admin/notification-preferences' },
{ n: 'getDefaultUserSettings', r: () => adminApi.getDefaultUserSettings(), e: 'GET /api/admin/default-user-settings' },
{ n: 'updateDefaultUserSettings', r: () => adminApi.updateDefaultUserSettings({ language: 'de' }), e: 'PUT /api/admin/default-user-settings' },
{ n: 'mcpTokens', r: () => adminApi.mcpTokens(), e: 'GET /api/admin/mcp-tokens' },
{ n: 'deleteMcpToken', r: () => adminApi.deleteMcpToken(4), e: 'DELETE /api/admin/mcp-tokens/4' },
{ n: 'oauthSessions', r: () => adminApi.oauthSessions(), e: 'GET /api/admin/oauth-sessions' },
{ n: 'revokeOAuthSession', r: () => adminApi.revokeOAuthSession(4), e: 'DELETE /api/admin/oauth-sessions/4' },
{ n: 'listInvites', r: () => adminApi.listInvites(), e: 'GET /api/admin/invites' },
{ n: 'listInviteTrips', r: () => adminApi.listInviteTrips(), e: 'GET /api/admin/invites/trips' },
{ n: 'createInvite', r: () => adminApi.createInvite({ max_uses: 3 }), e: 'POST /api/admin/invites' },
{ n: 'deleteInvite', r: () => adminApi.deleteInvite(8), e: 'DELETE /api/admin/invites/8' },
{ n: 'auditLog', r: () => adminApi.auditLog(), e: 'GET /api/admin/audit-log' },
])
})
it('FE-APISURF-011: adminApi maps the plugin management endpoints', async () => {
await assertCalls([
{ n: 'plugins', r: () => adminApi.plugins(), e: 'GET /api/admin/plugins' },
{ n: 'pluginBrowse', r: () => adminApi.pluginBrowse(), e: 'GET /api/admin/plugins/registry' },
{ n: 'pluginDetail', r: () => adminApi.pluginDetail('trek/koffi'), e: 'GET /api/admin/plugins/registry/trek%2Fkoffi' },
{ n: 'pluginInstall', r: () => adminApi.pluginInstall('koffi', { version: '1.0.0' }), e: 'POST /api/admin/plugins/install' },
{ n: 'pluginActivate', r: () => adminApi.pluginActivate('koffi'), e: 'POST /api/admin/plugins/koffi/activate' },
{ n: 'pluginDeactivate', r: () => adminApi.pluginDeactivate('koffi'), e: 'POST /api/admin/plugins/koffi/deactivate' },
{ n: 'pluginUpdate', r: () => adminApi.pluginUpdate('koffi'), e: 'POST /api/admin/plugins/koffi/update' },
{ n: 'pluginRetrust', r: () => adminApi.pluginRetrust('koffi', '2.0.0', 'PUBKEY'), e: 'POST /api/admin/plugins/koffi/retrust' },
{ n: 'pluginUninstall', r: () => adminApi.pluginUninstall('koffi', true), e: 'POST /api/admin/plugins/koffi/uninstall' },
{ n: 'pluginRescan', r: () => adminApi.pluginRescan(), e: 'POST /api/admin/plugins/rescan' },
{ n: 'pluginLink', r: () => adminApi.pluginLink('/srv/plugin'), e: 'POST /api/admin/plugins/link' },
{ n: 'pluginReload', r: () => adminApi.pluginReload('koffi'), e: 'POST /api/admin/plugins/koffi/reload' },
{ n: 'pluginEgressHosts', r: () => adminApi.pluginEgressHosts('koffi'), e: 'GET /api/admin/plugins/koffi/egress-hosts' },
{ n: 'pluginSetEgressHosts', r: () => adminApi.pluginSetEgressHosts('koffi', ['a.example']), e: 'PUT /api/admin/plugins/koffi/egress-hosts' },
{ n: 'pluginErrors', r: () => adminApi.pluginErrors('koffi'), e: 'GET /api/admin/plugins/koffi/errors' },
{ n: 'pluginAudit', r: () => adminApi.pluginAudit('koffi'), e: 'GET /api/admin/plugins/koffi/audit' },
{ n: 'llmLocalModels', r: () => adminApi.llmLocalModels('http://ollama:11434'), e: 'GET /api/admin/llm/local/models' },
])
})
it('FE-APISURF-012: adminApi maps the packing-template endpoints', async () => {
await assertCalls([
{ n: 'packingTemplates', r: () => adminApi.packingTemplates(), e: 'GET /api/admin/packing-templates' },
{ n: 'getPackingTemplate', r: () => adminApi.getPackingTemplate(1), e: 'GET /api/admin/packing-templates/1' },
{ n: 'createPackingTemplate', r: () => adminApi.createPackingTemplate({ name: 'Ski' }), e: 'POST /api/admin/packing-templates' },
{ n: 'updatePackingTemplate', r: () => adminApi.updatePackingTemplate(1, { name: 'Ski 2' }), e: 'PUT /api/admin/packing-templates/1' },
{ n: 'deletePackingTemplate', r: () => adminApi.deletePackingTemplate(1), e: 'DELETE /api/admin/packing-templates/1' },
{ n: 'addTemplateCategory', r: () => adminApi.addTemplateCategory(1, { name: 'Clothes' }), e: 'POST /api/admin/packing-templates/1/categories' },
{ n: 'updateTemplateCategory', r: () => adminApi.updateTemplateCategory(1, 2, { name: 'Wear' }), e: 'PUT /api/admin/packing-templates/1/categories/2' },
{ n: 'deleteTemplateCategory', r: () => adminApi.deleteTemplateCategory(1, 2), e: 'DELETE /api/admin/packing-templates/1/categories/2' },
{ n: 'addTemplateItem', r: () => adminApi.addTemplateItem(1, 2, { name: 'Gloves' }), e: 'POST /api/admin/packing-templates/1/categories/2/items' },
{ n: 'updateTemplateItem', r: () => adminApi.updateTemplateItem(1, 3, { name: 'Mittens' }), e: 'PUT /api/admin/packing-templates/1/items/3' },
{ n: 'deleteTemplateItem', r: () => adminApi.deleteTemplateItem(1, 3), e: 'DELETE /api/admin/packing-templates/1/items/3' },
])
})
it('FE-APISURF-013: pluginsApi maps every host-mediated plugin endpoint', async () => {
await assertCalls([
{ n: 'active', r: () => pluginsApi.active(), e: 'GET /api/plugins' },
{ n: 'placeDetails', r: () => pluginsApi.placeDetails(5), e: 'GET /api/place-details/5' },
{ n: 'tripWarnings', r: () => pluginsApi.tripWarnings(1), e: 'GET /api/trip-warnings/1' },
{ n: 'viewContributions', r: () => pluginsApi.viewContributions('places', 1), e: 'GET /api/view-contributions/places/1' },
{ n: 'mapMarkers', r: () => pluginsApi.mapMarkers(1), e: 'GET /api/map-markers/1' },
{ n: 'mapLayers', r: () => pluginsApi.mapLayers(1), e: 'GET /api/map-layers/1' },
{ n: 'pluginRoute', r: () => pluginsApi.pluginRoute('koffi', 'ev', { tripId: 1, waypoints: [{ lat: 1, lng: 2 }] }), e: 'POST /api/plugin-routes/koffi/ev' },
{ n: 'daySchedule', r: () => pluginsApi.daySchedule(1), e: 'GET /api/day-schedule/1' },
{ n: 'pdfSections', r: () => pluginsApi.pdfSections(1), e: 'GET /api/pdf-sections/1' },
{ n: 'atlasLayers', r: () => pluginsApi.atlasLayers(), e: 'GET /api/atlas-layers' },
{ n: 'journalEntryRows', r: () => pluginsApi.journalEntryRows(9), e: 'GET /api/journal-entry-rows/9' },
{ n: 'tripCardContributions', r: () => pluginsApi.tripCardContributions([1, 2]), e: 'GET /api/trip-card-contributions' },
{ n: 'myActivity', r: () => pluginsApi.myActivity(), e: 'GET /api/plugin-activity' },
{ n: 'userSettings', r: () => pluginsApi.userSettings('koffi'), e: 'GET /api/plugin-settings/koffi' },
{ n: 'runAction', r: () => pluginsApi.runAction('koffi', 'test connection'), e: 'POST /api/plugin-settings/koffi/actions/test%20connection' },
{ n: 'saveUserSettings', r: () => pluginsApi.saveUserSettings('koffi', { key: 'v' }), e: 'POST /api/plugin-settings/koffi' },
{ n: 'oauthStatus', r: () => pluginsApi.oauthStatus('koffi'), e: 'GET /api/plugin-oauth/koffi/status' },
{ n: 'oauthConnect', r: () => pluginsApi.oauthConnect('koffi'), e: 'POST /api/plugin-oauth/koffi/connect' },
{ n: 'oauthDisconnect', r: () => pluginsApi.oauthDisconnect('koffi'), e: 'POST /api/plugin-oauth/koffi/disconnect' },
])
})
it('FE-APISURF-014: airtrailApi maps the integration endpoints', async () => {
await assertCalls([
{ n: 'getSettings', r: () => airtrailApi.getSettings(), e: 'GET /api/integrations/airtrail/settings' },
{ n: 'saveSettings', r: () => airtrailApi.saveSettings({ url: 'https://at' }), e: 'PUT /api/integrations/airtrail/settings' },
{ n: 'status', r: () => airtrailApi.status(), e: 'GET /api/integrations/airtrail/status' },
{ n: 'test', r: () => airtrailApi.test({ url: 'https://at' }), e: 'POST /api/integrations/airtrail/test' },
{ n: 'sync', r: () => airtrailApi.sync(), e: 'POST /api/integrations/airtrail/sync' },
{ n: 'flights', r: () => airtrailApi.flights(), e: 'GET /api/integrations/airtrail/flights' },
{ n: 'import', r: () => airtrailApi.import(1, ['f1']), e: 'POST /api/trips/1/reservations/import/airtrail' },
])
})
it('FE-APISURF-015: journeyApi maps journal, entry and photo endpoints', async () => {
await assertCalls([
{ n: 'list', r: () => journeyApi.list(), e: 'GET /api/journeys' },
{ n: 'create', r: () => journeyApi.create({ title: 'Asia' }), e: 'POST /api/journeys' },
{ n: 'get', r: () => journeyApi.get(2), e: 'GET /api/journeys/2' },
{ n: 'update', r: () => journeyApi.update(2, { title: 'Asia 24' }), e: 'PATCH /api/journeys/2' },
{ n: 'delete', r: () => journeyApi.delete(2), e: 'DELETE /api/journeys/2' },
{ n: 'suggestions', r: () => journeyApi.suggestions(), e: 'GET /api/journeys/suggestions' },
{ n: 'availableTrips', r: () => journeyApi.availableTrips(), e: 'GET /api/journeys/available-trips' },
{ n: 'addTrip', r: () => journeyApi.addTrip(2, 1), e: 'POST /api/journeys/2/trips' },
{ n: 'removeTrip', r: () => journeyApi.removeTrip(2, 1), e: 'DELETE /api/journeys/2/trips/1' },
{ n: 'listEntries', r: () => journeyApi.listEntries(2), e: 'GET /api/journeys/2/entries' },
{ n: 'createEntry', r: () => journeyApi.createEntry(2, { title: 'Day 1' }), e: 'POST /api/journeys/2/entries' },
{ n: 'updateEntry', r: () => journeyApi.updateEntry(9, { title: 'Day 2' }), e: 'PATCH /api/journeys/entries/9' },
{ n: 'deleteEntry', r: () => journeyApi.deleteEntry(9), e: 'DELETE /api/journeys/entries/9' },
{ n: 'reorderEntries', r: () => journeyApi.reorderEntries(2, [9, 8]), e: 'PUT /api/journeys/2/entries/reorder' },
{ n: 'addProviderPhotosToGallery', r: () => journeyApi.addProviderPhotosToGallery(2, 'immich', ['a1']), e: 'POST /api/journeys/2/gallery/provider-photos' },
{ n: 'addProviderPhoto', r: () => journeyApi.addProviderPhoto(9, 'immich', 'a1'), e: 'POST /api/journeys/entries/9/provider-photos' },
{ n: 'addProviderPhotos', r: () => journeyApi.addProviderPhotos(9, 'immich', ['a1']), e: 'POST /api/journeys/entries/9/provider-photos' },
{ n: 'linkPhoto', r: () => journeyApi.linkPhoto(9, 11), e: 'POST /api/journeys/entries/9/link-photo' },
{ n: 'unlinkPhoto', r: () => journeyApi.unlinkPhoto(9, 11), e: 'DELETE /api/journeys/entries/9/photos/11' },
{ n: 'deleteGalleryPhoto', r: () => journeyApi.deleteGalleryPhoto(2, 11), e: 'DELETE /api/journeys/2/gallery/11' },
{ n: 'updatePhoto', r: () => journeyApi.updatePhoto(11, { caption: 'x' }), e: 'PATCH /api/journeys/photos/11' },
{ n: 'deletePhoto', r: () => journeyApi.deletePhoto(11), e: 'DELETE /api/journeys/photos/11' },
{ n: 'addContributor', r: () => journeyApi.addContributor(2, 4, 'editor'), e: 'POST /api/journeys/2/contributors' },
{ n: 'updateContributor', r: () => journeyApi.updateContributor(2, 4, 'viewer'), e: 'PATCH /api/journeys/2/contributors/4' },
{ n: 'removeContributor', r: () => journeyApi.removeContributor(2, 4), e: 'DELETE /api/journeys/2/contributors/4' },
{ n: 'updatePreferences', r: () => journeyApi.updatePreferences(2, { hide_skeletons: true }), e: 'PATCH /api/journeys/2/preferences' },
{ n: 'getShareLink', r: () => journeyApi.getShareLink(2), e: 'GET /api/journeys/2/share-link' },
{ n: 'createShareLink', r: () => journeyApi.createShareLink(2, { share_map: true }), e: 'POST /api/journeys/2/share-link' },
{ n: 'deleteShareLink', r: () => journeyApi.deleteShareLink(2), e: 'DELETE /api/journeys/2/share-link' },
{ n: 'getPublicJourney', r: () => journeyApi.getPublicJourney('pub-tok'), e: 'GET /api/public/journey/pub-tok' },
])
})
it('FE-APISURF-016: mapsApi and airportsApi map the geo endpoints', async () => {
await assertCalls([
{ n: 'maps.search', r: () => mapsApi.search('Rome'), e: 'POST /api/maps/search' },
{ n: 'maps.autocomplete', r: () => mapsApi.autocomplete('Rom'), e: 'POST /api/maps/autocomplete' },
{ n: 'maps.details', r: () => mapsApi.details('place/1'), e: 'GET /api/maps/details/place%2F1' },
{ n: 'maps.placePhoto', r: () => mapsApi.placePhoto('place/1'), e: 'GET /api/maps/place-photo/place%2F1' },
{ n: 'maps.reverse', r: () => mapsApi.reverse(41.9, 12.5), e: 'GET /api/maps/reverse' },
{ n: 'maps.resolveUrl', r: () => mapsApi.resolveUrl('https://maps.app.goo.gl/x'), e: 'POST /api/maps/resolve-url' },
{ n: 'maps.pois', r: () => mapsApi.pois('cafe', { south: 1, west: 2, north: 3, east: 4 }), e: 'GET /api/maps/pois' },
{ n: 'airports.search', r: () => airportsApi.search('BER'), e: 'GET /api/airports/search' },
{ n: 'airports.byIata', r: () => airportsApi.byIata('b/er'), e: 'GET /api/airports/b%2Fer' },
])
})
it('FE-APISURF-017: budgetApi maps item, member and settlement endpoints', async () => {
await assertCalls([
{ n: 'list', r: () => budgetApi.list(1), e: 'GET /api/trips/1/budget' },
{ n: 'create', r: () => budgetApi.create(1, { name: 'Hotel' }), e: 'POST /api/trips/1/budget' },
{ n: 'update', r: () => budgetApi.update(1, 2, { name: 'Hostel' }), e: 'PUT /api/trips/1/budget/2' },
{ n: 'delete', r: () => budgetApi.delete(1, 2), e: 'DELETE /api/trips/1/budget/2' },
{ n: 'setMembers', r: () => budgetApi.setMembers(1, 2, [4, 5]), e: 'PUT /api/trips/1/budget/2/members' },
{ n: 'togglePaid', r: () => budgetApi.togglePaid(1, 2, 4, true), e: 'PUT /api/trips/1/budget/2/members/4/paid' },
{ n: 'setPayers', r: () => budgetApi.setPayers(1, 2, [{ user_id: 4, amount: 10 }]), e: 'PUT /api/trips/1/budget/2/payers' },
{ n: 'perPersonSummary', r: () => budgetApi.perPersonSummary(1), e: 'GET /api/trips/1/budget/summary/per-person' },
{ n: 'settlement', r: () => budgetApi.settlement(1), e: 'GET /api/trips/1/budget/settlement' },
{ n: 'createSettlement', r: () => budgetApi.createSettlement(1, { from_user_id: 4, to_user_id: 5, amount: 10 }), e: 'POST /api/trips/1/budget/settlements' },
{ n: 'updateSettlement', r: () => budgetApi.updateSettlement(1, 6, { from_user_id: 4, to_user_id: 5, amount: 12 }), e: 'PUT /api/trips/1/budget/settlements/6' },
{ n: 'deleteSettlement', r: () => budgetApi.deleteSettlement(1, 6), e: 'DELETE /api/trips/1/budget/settlements/6' },
{ n: 'reorderItems', r: () => budgetApi.reorderItems(1, [2, 3]), e: 'PUT /api/trips/1/budget/reorder/items' },
{ n: 'reorderCategories', r: () => budgetApi.reorderCategories(1, ['Food']), e: 'PUT /api/trips/1/budget/reorder/categories' },
])
})
it('FE-APISURF-018: filesApi maps file, trash and link endpoints', async () => {
await assertCalls([
{ n: 'list', r: () => filesApi.list(1), e: 'GET /api/trips/1/files' },
{ n: 'update', r: () => filesApi.update(1, 3, { description: 'x' }), e: 'PUT /api/trips/1/files/3' },
{ n: 'delete', r: () => filesApi.delete(1, 3), e: 'DELETE /api/trips/1/files/3' },
{ n: 'toggleStar', r: () => filesApi.toggleStar(1, 3), e: 'PATCH /api/trips/1/files/3/star' },
{ n: 'restore', r: () => filesApi.restore(1, 3), e: 'POST /api/trips/1/files/3/restore' },
{ n: 'permanentDelete', r: () => filesApi.permanentDelete(1, 3), e: 'DELETE /api/trips/1/files/3/permanent' },
{ n: 'emptyTrash', r: () => filesApi.emptyTrash(1), e: 'DELETE /api/trips/1/files/trash/empty' },
{ n: 'addLink', r: () => filesApi.addLink(1, 3, { place_id: 5 }), e: 'POST /api/trips/1/files/3/link' },
{ n: 'removeLink', r: () => filesApi.removeLink(1, 3, 7), e: 'DELETE /api/trips/1/files/3/link/7' },
{ n: 'getLinks', r: () => filesApi.getLinks(1, 3), e: 'GET /api/trips/1/files/3/links' },
])
})
it('FE-APISURF-019: reservationsApi and accommodationsApi map booking endpoints', async () => {
await assertCalls([
{ n: 'reservations.list', r: () => reservationsApi.list(1), e: 'GET /api/trips/1/reservations' },
{ n: 'reservations.upcoming', r: () => reservationsApi.upcoming(), e: 'GET /api/reservations/upcoming' },
{ n: 'reservations.create', r: () => reservationsApi.create(1, { title: 'Hotel' }), e: 'POST /api/trips/1/reservations' },
{ n: 'reservations.update', r: () => reservationsApi.update(1, 2, { title: 'Hostel' }), e: 'PUT /api/trips/1/reservations/2' },
{ n: 'reservations.delete', r: () => reservationsApi.delete(1, 2), e: 'DELETE /api/trips/1/reservations/2' },
{ n: 'reservations.setTravelers', r: () => reservationsApi.setTravelers(1, 2, [4]), e: 'PUT /api/trips/1/reservations/2/travelers' },
{ n: 'reservations.updatePositions', r: () => reservationsApi.updatePositions(1, [{ id: 2, day_plan_position: 0 }], 3), e: 'PUT /api/trips/1/reservations/positions' },
{ n: 'reservations.importBookingConfirm', r: () => reservationsApi.importBookingConfirm(1, []), e: 'POST /api/trips/1/reservations/import/booking/confirm' },
{ n: 'reservations.importJobStatus', r: () => reservationsApi.importJobStatus(1, 'job-1'), e: 'GET /api/trips/1/reservations/import/jobs/job-1' },
{ n: 'accommodations.list', r: () => accommodationsApi.list(1), e: 'GET /api/trips/1/accommodations' },
{ n: 'accommodations.create', r: () => accommodationsApi.create(1, { place_id: 5, start_day_id: 1, end_day_id: 2 }), e: 'POST /api/trips/1/accommodations' },
{ n: 'accommodations.update', r: () => accommodationsApi.update(1, 4, { end_day_id: 3 }), e: 'PUT /api/trips/1/accommodations/4' },
{ n: 'accommodations.delete', r: () => accommodationsApi.delete(1, 4), e: 'DELETE /api/trips/1/accommodations/4' },
])
})
it('FE-APISURF-020: collabApi maps note, poll and message endpoints', async () => {
await assertCalls([
{ n: 'getNotes', r: () => collabApi.getNotes(1), e: 'GET /api/trips/1/collab/notes' },
{ n: 'createNote', r: () => collabApi.createNote(1, { title: 'Ideas' }), e: 'POST /api/trips/1/collab/notes' },
{ n: 'updateNote', r: () => collabApi.updateNote(1, 2, { title: 'More' }), e: 'PUT /api/trips/1/collab/notes/2' },
{ n: 'deleteNote', r: () => collabApi.deleteNote(1, 2), e: 'DELETE /api/trips/1/collab/notes/2' },
{ n: 'deleteNoteFile', r: () => collabApi.deleteNoteFile(1, 2, 3), e: 'DELETE /api/trips/1/collab/notes/2/files/3' },
{ n: 'getPolls', r: () => collabApi.getPolls(1), e: 'GET /api/trips/1/collab/polls' },
{ n: 'createPoll', r: () => collabApi.createPoll(1, { question: 'Where?', options: ['A', 'B'] }), e: 'POST /api/trips/1/collab/polls' },
{ n: 'votePoll', r: () => collabApi.votePoll(1, 2, 1), e: 'POST /api/trips/1/collab/polls/2/vote' },
{ n: 'closePoll', r: () => collabApi.closePoll(1, 2), e: 'PUT /api/trips/1/collab/polls/2/close' },
{ n: 'deletePoll', r: () => collabApi.deletePoll(1, 2), e: 'DELETE /api/trips/1/collab/polls/2' },
{ n: 'getMessages', r: () => collabApi.getMessages(1), e: 'GET /api/trips/1/collab/messages' },
{ n: 'sendMessage', r: () => collabApi.sendMessage(1, { text: 'hi' }), e: 'POST /api/trips/1/collab/messages' },
{ n: 'deleteMessage', r: () => collabApi.deleteMessage(1, 2), e: 'DELETE /api/trips/1/collab/messages/2' },
{ n: 'reactMessage', r: () => collabApi.reactMessage(1, 2, '👍'), e: 'POST /api/trips/1/collab/messages/2/react' },
{ n: 'linkPreview', r: () => collabApi.linkPreview(1, 'https://x.test/a?b=1'), e: 'GET /api/trips/1/collab/link-preview' },
])
})
it('FE-APISURF-021: the remaining namespaces map their endpoints', async () => {
await assertCalls([
{ n: 'addons.enabled', r: () => addonsApi.enabled(), e: 'GET /api/addons' },
{ n: 'health.features', r: () => healthApi.features(), e: 'GET /api/health/features' },
{ n: 'weather.get', r: () => weatherApi.get(41.9, 12.5, '2026-06-01'), e: 'GET /api/weather' },
{ n: 'weather.getCurrent', r: () => weatherApi.getCurrent(41.9, 12.5), e: 'GET /api/weather' },
{ n: 'weather.getDetailed', r: () => weatherApi.getDetailed(41.9, 12.5, '2026-06-01'), e: 'GET /api/weather/detailed' },
{ n: 'config.getPublicConfig', r: () => configApi.getPublicConfig(), e: 'GET /api/config' },
{ n: 'help.index', r: () => helpApi.index(), e: 'GET /api/help/index' },
{ n: 'help.page', r: () => helpApi.page('getting started'), e: 'GET /api/help/page/getting%20started' },
{ n: 'settings.get', r: () => settingsApi.get(), e: 'GET /api/settings' },
{ n: 'settings.set', r: () => settingsApi.set('theme', 'dark'), e: 'PUT /api/settings' },
{ n: 'settings.setBulk', r: () => settingsApi.setBulk({ theme: 'dark' }), e: 'POST /api/settings/bulk' },
{ n: 'backup.list', r: () => backupApi.list(), e: 'GET /api/backup/list' },
{ n: 'backup.create', r: () => backupApi.create(), e: 'POST /api/backup/create' },
{ n: 'backup.delete', r: () => backupApi.delete('b.zip'), e: 'DELETE /api/backup/b.zip' },
{ n: 'backup.restore', r: () => backupApi.restore('b.zip'), e: 'POST /api/backup/restore/b.zip' },
{ n: 'backup.getAutoSettings', r: () => backupApi.getAutoSettings(), e: 'GET /api/backup/auto-settings' },
{ n: 'backup.setAutoSettings', r: () => backupApi.setAutoSettings({ enabled: true }), e: 'PUT /api/backup/auto-settings' },
{ n: 'share.getLink', r: () => shareApi.getLink(1), e: 'GET /api/trips/1/share-link' },
{ n: 'share.createLink', r: () => shareApi.createLink(1, { edit: false }), e: 'POST /api/trips/1/share-link' },
{ n: 'share.deleteLink', r: () => shareApi.deleteLink(1), e: 'DELETE /api/trips/1/share-link' },
{ n: 'share.getSharedTrip', r: () => shareApi.getSharedTrip('tok'), e: 'GET /api/shared/tok' },
{ n: 'transit.geocode', r: () => transitApi.geocode('Roma Termini'), e: 'GET /api/transit/geocode' },
{ n: 'transit.plan', r: () => transitApi.plan({ from: 'a', to: 'b' }), e: 'GET /api/transit/plan' },
{ n: 'tripInvite.getLink', r: () => tripInviteApi.getLink(1), e: 'GET /api/trips/1/invite-link' },
{ n: 'tripInvite.createLink', r: () => tripInviteApi.createLink(1, 7), e: 'POST /api/trips/1/invite-link' },
{ n: 'tripInvite.deleteLink', r: () => tripInviteApi.deleteLink(1), e: 'DELETE /api/trips/1/invite-link' },
{ n: 'tripInvite.preview', r: () => tripInviteApi.preview('tok'), e: 'GET /api/trip-invites/tok' },
{ n: 'tripInvite.accept', r: () => tripInviteApi.accept('tok'), e: 'POST /api/trip-invites/tok/accept' },
{ n: 'notifications.getPreferences', r: () => notificationsApi.getPreferences(), e: 'GET /api/notifications/preferences' },
{ n: 'notifications.updatePreferences', r: () => notificationsApi.updatePreferences({ email: { trip_invite: true } }), e: 'PUT /api/notifications/preferences' },
{ n: 'notifications.testSmtp', r: () => notificationsApi.testSmtp('a@b.c'), e: 'POST /api/notifications/test-smtp' },
{ n: 'notifications.testWebhook', r: () => notificationsApi.testWebhook('https://hook'), e: 'POST /api/notifications/test-webhook' },
{ n: 'notifications.testNtfy', r: () => notificationsApi.testNtfy({ topic: 't' }), e: 'POST /api/notifications/test-ntfy' },
{ n: 'notifications.testChannel', r: () => notificationsApi.testChannel('plugin/ch'), e: 'POST /api/notifications/test/plugin%2Fch' },
{ n: 'inApp.list', r: () => inAppNotificationsApi.list(), e: 'GET /api/notifications/in-app' },
{ n: 'inApp.unreadCount', r: () => inAppNotificationsApi.unreadCount(), e: 'GET /api/notifications/in-app/unread-count' },
{ n: 'inApp.markRead', r: () => inAppNotificationsApi.markRead(3), e: 'PUT /api/notifications/in-app/3/read' },
{ n: 'inApp.markUnread', r: () => inAppNotificationsApi.markUnread(3), e: 'PUT /api/notifications/in-app/3/unread' },
{ n: 'inApp.markAllRead', r: () => inAppNotificationsApi.markAllRead(), e: 'PUT /api/notifications/in-app/read-all' },
{ n: 'inApp.delete', r: () => inAppNotificationsApi.delete(3), e: 'DELETE /api/notifications/in-app/3' },
{ n: 'inApp.deleteAll', r: () => inAppNotificationsApi.deleteAll(), e: 'DELETE /api/notifications/in-app/all' },
{ n: 'inApp.respond', r: () => inAppNotificationsApi.respond(3, 'positive'), e: 'POST /api/notifications/in-app/3/respond' },
])
})
})
describe('client > request payloads', () => {
it('FE-APISURF-022: reorder helpers wrap their ids in the contract field', async () => {
expect((await traceOne(() => daysApi.reorder(1, [3, 1, 2]))).body).toEqual({ orderedIds: [3, 1, 2] })
expect((await traceOne(() => packingApi.reorder(1, [2, 1]))).body).toEqual({ orderedIds: [2, 1] })
expect((await traceOne(() => todoApi.reorder(1, [9]))).body).toEqual({ orderedIds: [9] })
expect((await traceOne(() => budgetApi.reorderItems(1, [4, 5]))).body).toEqual({ orderedIds: [4, 5] })
expect((await traceOne(() => budgetApi.reorderCategories(1, ['Food', 'Fun']))).body)
.toEqual({ orderedCategories: ['Food', 'Fun'] })
expect((await traceOne(() => journeyApi.reorderEntries(2, [8, 7]))).body).toEqual({ orderedIds: [8, 7] })
})
it('FE-APISURF-023: user-id collections are sent as user_ids', async () => {
expect((await traceOne(() => assignmentsApi.setParticipants(1, 7, [4, 5]))).body).toEqual({ user_ids: [4, 5] })
expect((await traceOne(() => budgetApi.setMembers(1, 2, [4]))).body).toEqual({ user_ids: [4] })
expect((await traceOne(() => packingApi.setBagMembers(1, 2, [6]))).body).toEqual({ user_ids: [6] })
expect((await traceOne(() => reservationsApi.setTravelers(1, 2, [4, 6]))).body).toEqual({ user_ids: [4, 6] })
})
it('FE-APISURF-024: single-value helpers wrap their argument in the documented key', async () => {
expect((await traceOne(() => authApi.updateMapsKey(null))).body).toEqual({ maps_api_key: null })
expect((await traceOne(() => tripsApi.addMember(1, 'bob@x.test'))).body).toEqual({ identifier: 'bob@x.test' })
expect((await traceOne(() => tripsApi.transferOwnership(1, 9))).body).toEqual({ newOwnerId: 9 })
expect((await traceOne(() => tripsApi.createGuest(1, 'Anna'))).body).toEqual({ name: 'Anna' })
expect((await traceOne(() => daysApi.updateTransport(1, 2, 'walk'))).body).toEqual({ transport_mode: 'walk' })
expect((await traceOne(() => assignmentsApi.updateTransport(1, 7, null))).body).toEqual({ transport_mode: null })
expect((await traceOne(() => collabApi.votePoll(1, 2, 3))).body).toEqual({ option_index: 3 })
expect((await traceOne(() => collabApi.reactMessage(1, 2, '🎉'))).body).toEqual({ emoji: '🎉' })
expect((await traceOne(() => settingsApi.set('theme', 'dark'))).body).toEqual({ key: 'theme', value: 'dark' })
expect((await traceOne(() => settingsApi.setBulk({ a: 1 }))).body).toEqual({ settings: { a: 1 } })
expect((await traceOne(() => budgetApi.togglePaid(1, 2, 4, false))).body).toEqual({ paid: false })
expect((await traceOne(() => adminApi.updateBagTracking(true))).body).toEqual({ enabled: true })
expect((await traceOne(() => adminApi.updatePermissions({ edit: 'owner' }))).body)
.toEqual({ permissions: { edit: 'owner' } })
expect((await traceOne(() => pluginsApi.saveUserSettings('koffi', { k: 'v' }))).body)
.toEqual({ config: { k: 'v' } })
})
it('FE-APISURF-025: tripsApi.archive/unarchive send the is_archived flag', async () => {
expect((await traceOne(() => tripsApi.archive(3))).body).toEqual({ is_archived: true })
expect((await traceOne(() => tripsApi.unarchive(3))).body).toEqual({ is_archived: false })
})
it('FE-APISURF-026: placesApi bulk operations merge ids with the patch', async () => {
expect((await traceOne(() => placesApi.bulkDelete(1, [5, 6]))).body).toEqual({ ids: [5, 6] })
expect((await traceOne(() => placesApi.bulkUpdate(1, [5], { category_id: null }))).body)
.toEqual({ ids: [5], category_id: null })
})
it('FE-APISURF-027: placesApi.rate deletes on null and PUTs the value otherwise', async () => {
const cleared = await traceOne(() => placesApi.rate(1, 5, null))
expect(cleared.method).toBe('DELETE')
expect(cleared.url).toBe('/api/trips/1/places/5/rating')
const set = await traceOne(() => placesApi.rate(1, 5, 4))
expect(set.method).toBe('PUT')
expect(set.url).toBe('/api/trips/1/places/5/rating')
expect(set.body).toEqual({ rating: 4 })
})
it('FE-APISURF-028: airtrailApi.import only sends connections when there are any', async () => {
expect((await traceOne(() => airtrailApi.import(1, ['f1', 'f2']))).body).toEqual({ flightIds: ['f1', 'f2'] })
expect((await traceOne(() => airtrailApi.import(1, ['f1'], []))).body).toEqual({ flightIds: ['f1'] })
expect((await traceOne(() => airtrailApi.import(1, ['f1', 'f2'], [['f1', 'f2']]))).body)
.toEqual({ flightIds: ['f1', 'f2'], connections: [['f1', 'f2']] })
})
it('FE-APISURF-029: journeyApi provider-photo calls omit optional passphrase and media types', async () => {
expect((await traceOne(() => journeyApi.addProviderPhotosToGallery(2, 'immich', ['a1']))).body)
.toEqual({ provider: 'immich', asset_ids: ['a1'] })
expect((await traceOne(() => journeyApi.addProviderPhotosToGallery(2, 'immich', ['a1'], 'secret', ['video']))).body)
.toEqual({ provider: 'immich', asset_ids: ['a1'], passphrase: 'secret', media_types: ['video'] })
expect((await traceOne(() => journeyApi.addProviderPhoto(9, 'immich', 'a1', 'cap', 'secret'))).body)
.toEqual({ provider: 'immich', asset_id: 'a1', caption: 'cap', passphrase: 'secret' })
expect((await traceOne(() => journeyApi.addProviderPhotos(9, 'immich', ['a1'], 'cap'))).body)
.toEqual({ provider: 'immich', asset_ids: ['a1'], caption: 'cap' })
expect((await traceOne(() => journeyApi.addProviderPhotos(9, 'immich', ['a1'], 'cap', 'secret', ['image', 'video']))).body)
.toEqual({ provider: 'immich', asset_ids: ['a1'], caption: 'cap', passphrase: 'secret', media_types: ['image', 'video'] })
})
it('FE-APISURF-030: adminApi.pluginActivate only sends consent when granted', async () => {
expect((await traceOne(() => adminApi.pluginActivate('koffi'))).body).toEqual({})
expect((await traceOne(() => adminApi.pluginActivate('koffi', true))).body).toEqual({ consent: true })
})
it('FE-APISURF-031: adminApi.pluginInstall spreads its options next to the id', async () => {
expect((await traceOne(() => adminApi.pluginInstall('koffi'))).body).toEqual({ id: 'koffi' })
expect((await traceOne(() => adminApi.pluginInstall('koffi', { version: '2.0.0', withDependencies: true }))).body)
.toEqual({ id: 'koffi', version: '2.0.0', withDependencies: true })
})
it('FE-APISURF-032: tripInviteApi.createLink normalises a missing expiry to null', async () => {
expect((await traceOne(() => tripInviteApi.createLink(1))).body).toEqual({ expires_in_days: null })
expect((await traceOne(() => tripInviteApi.createLink(1, 14))).body).toEqual({ expires_in_days: 14 })
})
it('FE-APISURF-033: tripsApi.copy and shareApi.createLink default to an empty body', async () => {
expect((await traceOne(() => tripsApi.copy(3))).body).toEqual({})
expect((await traceOne(() => shareApi.createLink(1))).body).toEqual({})
})
it('FE-APISURF-034: authApi.passkey.delete sends the password in the DELETE body', async () => {
const rec = await traceOne(() => authApi.passkey.delete(3, 'hunter2'))
expect(rec.method).toBe('DELETE')
expect(rec.body).toEqual({ password: 'hunter2' })
})
})
describe('client > query parameters', () => {
it('FE-APISURF-035: tripsApi.list forwards arbitrary filters as query params', async () => {
const rec = await traceOne(() => tripsApi.list({ archived: true, q: 'rome' }))
const qs = new URLSearchParams(rec.url.split('?')[1])
expect(qs.get('archived')).toBe('true')
expect(qs.get('q')).toBe('rome')
})
it('FE-APISURF-036: filesApi.list only sets the trash flag when asked', async () => {
expect((await traceOne(() => filesApi.list(1))).url).toBe('/api/trips/1/files')
expect((await traceOne(() => filesApi.list(1, true))).url).toBe('/api/trips/1/files?trash=true')
})
it('FE-APISURF-037: budgetApi.settlement adds the base currency only when given', async () => {
expect((await traceOne(() => budgetApi.settlement(1))).url).toBe('/api/trips/1/budget/settlement')
expect((await traceOne(() => budgetApi.settlement(1, 'EUR'))).url).toBe('/api/trips/1/budget/settlement?base=EUR')
})
it('FE-APISURF-038: collabApi.getMessages appends the before cursor', async () => {
expect((await traceOne(() => collabApi.getMessages(1))).url).toBe('/api/trips/1/collab/messages')
expect((await traceOne(() => collabApi.getMessages(1, '2026-01-01'))).url)
.toBe('/api/trips/1/collab/messages?before=2026-01-01')
})
it('FE-APISURF-039: adminApi.pluginBrowse only sets refresh when forced', async () => {
expect((await traceOne(() => adminApi.pluginBrowse())).url).toBe('/api/admin/plugins/registry')
expect((await traceOne(() => adminApi.pluginBrowse(true))).url).toBe('/api/admin/plugins/registry?refresh=1')
})
it('FE-APISURF-040: adminApi.auditLog and llmLocalModels pass their params through', async () => {
const audit = await traceOne(() => adminApi.auditLog({ limit: 50, offset: 100 }))
expect(new URLSearchParams(audit.url.split('?')[1]).get('limit')).toBe('50')
expect(new URLSearchParams(audit.url.split('?')[1]).get('offset')).toBe('100')
const models = await traceOne(() => adminApi.llmLocalModels('http://ollama:11434'))
expect(new URLSearchParams(models.url.split('?')[1]).get('baseUrl')).toBe('http://ollama:11434')
})
it('FE-APISURF-041: mapsApi flattens the POI bbox into the query string', async () => {
const rec = await traceOne(() => mapsApi.pois('cafe', { south: 41.8, west: 12.4, north: 42.0, east: 12.6 }, 'de'))
const qs = new URLSearchParams(rec.url.split('?')[1])
expect(qs.get('category')).toBe('cafe')
expect(qs.get('south')).toBe('41.8')
expect(qs.get('west')).toBe('12.4')
expect(qs.get('north')).toBe('42')
expect(qs.get('east')).toBe('12.6')
expect(qs.get('lang')).toBe('de')
})
it('FE-APISURF-042: weatherApi sends lat/lng plus the date or language', async () => {
const forecast = await traceOne(() => weatherApi.get(41.9, 12.5, '2026-06-01'))
const fq = new URLSearchParams(forecast.url.split('?')[1])
expect([fq.get('lat'), fq.get('lng'), fq.get('date')]).toEqual(['41.9', '12.5', '2026-06-01'])
const current = await traceOne(() => weatherApi.getCurrent(41.9, 12.5, 'de'))
expect(new URLSearchParams(current.url.split('?')[1]).get('lang')).toBe('de')
})
it('FE-APISURF-043: pluginsApi joins trip ids and defaults the activity limit', async () => {
expect((await traceOne(() => pluginsApi.tripCardContributions([1, 2, 3]))).url)
.toBe('/api/trip-card-contributions?tripIds=1,2,3')
expect((await traceOne(() => pluginsApi.myActivity())).url).toBe('/api/plugin-activity?limit=200')
expect((await traceOne(() => pluginsApi.myActivity(5))).url).toBe('/api/plugin-activity?limit=5')
})
it('FE-APISURF-044: packing/todo category assignees encode the category name', async () => {
const packing = await traceOne(() => packingApi.setCategoryAssignees(1, 'Rain gear/Wet', [4]))
expect(packing.url).toBe('/api/trips/1/packing/category-assignees/Rain%20gear%2FWet')
expect(packing.body).toEqual({ user_ids: [4] })
const todo = await traceOne(() => todoApi.setCategoryAssignees(1, 'Before & after', [5]))
expect(todo.url).toBe('/api/trips/1/todo/category-assignees/Before%20%26%20after')
expect(todo.body).toEqual({ user_ids: [5] })
})
it('FE-APISURF-045: collabApi.linkPreview URL-encodes the previewed link', async () => {
const rec = await traceOne(() => collabApi.linkPreview(1, 'https://x.test/a?b=1&c=2'))
expect(rec.url).toBe('/api/trips/1/collab/link-preview?url=https%3A%2F%2Fx.test%2Fa%3Fb%3D1%26c%3D2')
})
})
describe('client > multipart uploads', () => {
// jsdom FormData bodies deadlock inside MSW, so uploads are asserted at the
// axios boundary instead (same approach as tests/integration/api/client.test.ts).
function spyPost() {
return vi.spyOn(apiClient, 'post')
.mockResolvedValue({ data: { ok: true } } as unknown as AxiosResponse)
}
it('FE-APISURF-046: every upload opts out of the 8s global timeout', async () => {
const post = spyPost()
const fd = new FormData()
await authApi.uploadAvatar(fd)
await tripsApi.uploadCover(3, fd)
await filesApi.upload(1, fd)
await journeyApi.uploadPhotos(9, fd)
await journeyApi.uploadGalleryPhotos(2, fd)
await journeyApi.uploadGalleryVideo(2, fd)
await journeyApi.uploadCover(2, fd)
await collabApi.uploadNoteFile(1, 2, fd)
expect(post.mock.calls.map(c => c[0])).toEqual([
'/auth/avatar',
'/trips/3/cover',
'/trips/1/files',
'/journeys/entries/9/photos',
'/journeys/2/gallery/photos',
'/journeys/2/gallery/video',
'/journeys/2/cover',
'/trips/1/collab/notes/2/files',
])
for (const call of post.mock.calls) {
expect(call[1]).toBeInstanceOf(FormData)
expect(call[2]).toMatchObject({ timeout: 0 })
expect((call[2] as { headers: Record<string, string> }).headers['Content-Type']).toBe('multipart/form-data')
}
})
it('FE-APISURF-047: postMultipart forwards progress, abort signal and idempotency key', async () => {
const post = spyPost()
const onUploadProgress = vi.fn((_e: unknown) => {})
const controller = new AbortController()
await filesApi.upload(1, new FormData(), {
onUploadProgress,
signal: controller.signal,
idempotencyKey: 'fixed-key',
})
const config = post.mock.calls[0][2] as {
headers: Record<string, string>
onUploadProgress?: unknown
signal?: AbortSignal
timeout: number
}
expect(config.headers['X-Idempotency-Key']).toBe('fixed-key')
expect(config.onUploadProgress).toBe(onUploadProgress)
expect(config.signal).toBe(controller.signal)
expect(config.timeout).toBe(0)
})
it('FE-APISURF-048: placesApi.uploadImage posts the file under the image field', async () => {
const post = spyPost()
const file = new File(['bytes'], 'shot.jpg', { type: 'image/jpeg' })
await placesApi.uploadImage(1, 5, file)
expect(post.mock.calls[0][0]).toBe('/trips/1/places/5/image')
const fd = post.mock.calls[0][1] as FormData
expect((fd.get('image') as File).name).toBe('shot.jpg')
})
it('FE-APISURF-049: placesApi.importGpx only appends the flags it was given', async () => {
const post = spyPost()
const file = new File(['<gpx/>'], 'track.gpx')
await placesApi.importGpx(1, file)
expect(post.mock.calls[0][0]).toBe('/trips/1/places/import/gpx')
const bare = post.mock.calls[0][1] as FormData
expect(bare.get('importWaypoints')).toBeNull()
expect(bare.get('importRoutes')).toBeNull()
expect(bare.get('importTracks')).toBeNull()
await placesApi.importGpx(1, file, { waypoints: true, routes: false, tracks: true })
const flagged = post.mock.calls[1][1] as FormData
expect(flagged.get('importWaypoints')).toBe('true')
expect(flagged.get('importRoutes')).toBe('false')
expect(flagged.get('importTracks')).toBe('true')
})
it('FE-APISURF-050: placesApi.importMapFile appends the point/path flags', async () => {
const post = spyPost()
const file = new File(['{}'], 'map.kml')
await placesApi.importMapFile(1, file)
expect(post.mock.calls[0][0]).toBe('/trips/1/places/import/map')
expect((post.mock.calls[0][1] as FormData).get('importPoints')).toBeNull()
await placesApi.importMapFile(1, file, { points: true, paths: false })
const flagged = post.mock.calls[1][1] as FormData
expect(flagged.get('importPoints')).toBe('true')
expect(flagged.get('importPaths')).toBe('false')
})
it('FE-APISURF-051: booking import posts every file plus the extraction mode', async () => {
const post = spyPost()
const files = [new File(['a'], 'a.pdf'), new File(['b'], 'b.pdf')]
await reservationsApi.importBookingPreview(1, files, 'force-ai')
expect(post.mock.calls[0][0]).toBe('/trips/1/reservations/import/booking')
const preview = post.mock.calls[0][1] as FormData
expect(preview.getAll('files')).toHaveLength(2)
expect(preview.get('mode')).toBe('force-ai')
await reservationsApi.importBookingAsync(1, files)
expect(post.mock.calls[1][0]).toBe('/trips/1/reservations/import/booking/async')
expect((post.mock.calls[1][1] as FormData).get('mode')).toBe('no-ai')
})
it('FE-APISURF-052: adminApi.pluginUpload and backupApi.uploadRestore name their form fields', async () => {
const post = spyPost()
await adminApi.pluginUpload(new File(['zip'], 'plugin.zip'))
expect(post.mock.calls[0][0]).toBe('/admin/plugins/upload')
expect(((post.mock.calls[0][1] as FormData).get('file') as File).name).toBe('plugin.zip')
await backupApi.uploadRestore(new File(['zip'], 'backup.zip'))
expect(post.mock.calls[1][0]).toBe('/backup/upload-restore')
expect(((post.mock.calls[1][1] as FormData).get('backup') as File).name).toBe('backup.zip')
})
})
+342
View File
@@ -0,0 +1,342 @@
// FE-API-COLLECTIONS-001 to FE-API-COLLECTIONS-032
//
// The Collections addon wrapper is thin, but every method encodes a URL, a verb and a
// request-body shape that the server contract depends on. These tests drive each method
// through MSW and pin the method + path + payload, plus the unwrapping of `r.data`.
import { describe, it, expect, beforeEach } from 'vitest'
import { http, HttpResponse, type JsonBodyType } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { collectionsApi } from './collections'
import type { Collection, CollectionLabel, CollectionPlace } from '@trek/shared'
const BASE = '/api/addons/collections'
const collection: Collection = { id: 1, owner_id: 1, name: 'Tokyo', place_count: 2, is_owner: true }
const place: CollectionPlace = { id: 10, collection_id: 1, name: 'Shibuya Crossing', status: 'want' }
const label: CollectionLabel = { id: 3, collection_id: 1, name: 'Food', color: '#ef4444' }
let requestUrl = ''
let requestBody: unknown
beforeEach(() => {
requestUrl = ''
requestBody = undefined
})
/** Records url + parsed JSON body of the intercepted request, then answers with `data`. */
function record<T extends JsonBodyType>(data: T) {
return async ({ request }: { request: Request }) => {
requestUrl = request.url
const text = await request.text()
if (text) {
try {
requestBody = JSON.parse(text)
} catch {
requestBody = text
}
}
return HttpResponse.json(data)
}
}
describe('collectionsApi', () => {
it('FE-API-COLLECTIONS-001: list() unwraps the collections + incomingInvites envelope', async () => {
server.use(http.get(BASE, record({ collections: [collection], incomingInvites: [] })))
const res = await collectionsApi.list()
expect(res.collections).toEqual([collection])
expect(res.incomingInvites).toEqual([])
})
it('FE-API-COLLECTIONS-002: get() requests the list by id', async () => {
server.use(http.get(`${BASE}/:id`, record({ collection, places: [place] })))
const res = await collectionsApi.get(1)
expect(requestUrl).toContain(`${BASE}/1`)
expect(res.places).toEqual([place])
expect(res.collection.name).toBe('Tokyo')
})
it('FE-API-COLLECTIONS-003: create() posts the create payload', async () => {
server.use(http.post(BASE, record({ collection })))
const res = await collectionsApi.create({ name: 'Tokyo', color: '#111827' })
expect(requestBody).toEqual({ name: 'Tokyo', color: '#111827' })
expect(res.collection.id).toBe(1)
})
it('FE-API-COLLECTIONS-004: update() patches the list by id', async () => {
server.use(http.patch(`${BASE}/:id`, record({ collection })))
const res = await collectionsApi.update(1, { name: 'Tokyo 2026' })
expect(requestUrl).toContain(`${BASE}/1`)
expect(requestBody).toEqual({ name: 'Tokyo 2026' })
expect(res.collection).toEqual(collection)
})
it('FE-API-COLLECTIONS-005: uploadCover() posts multipart to the cover endpoint', async () => {
server.use(http.post(`${BASE}/:id/cover`, record(collection)))
const fd = new FormData()
fd.append('cover', new File(['x'], 'cover.jpg'))
const res = await collectionsApi.uploadCover(1, fd)
expect(requestUrl).toContain(`${BASE}/1/cover`)
expect(res).toEqual(collection)
})
it('FE-API-COLLECTIONS-006: remove() deletes the list', async () => {
server.use(http.delete(`${BASE}/:id`, record({ success: true })))
const res = await collectionsApi.remove(4)
expect(requestUrl).toContain(`${BASE}/4`)
expect(res).toEqual({ success: true })
})
it('FE-API-COLLECTIONS-007: reorder() posts the ordered ids', async () => {
server.use(http.post(`${BASE}/reorder`, record({ success: true })))
await collectionsApi.reorder([3, 1, 2])
expect(requestBody).toEqual({ orderedIds: [3, 1, 2] })
})
it('FE-API-COLLECTIONS-008: savePlace() posts the place payload', async () => {
server.use(http.post(`${BASE}/places`, record({ place })))
const res = await collectionsApi.savePlace({ collection_id: 1, name: 'Shibuya Crossing', force: true })
expect(requestBody).toEqual({ collection_id: 1, name: 'Shibuya Crossing', force: true })
expect(res.place).toEqual(place)
})
it('FE-API-COLLECTIONS-009: saveFromTrip() posts the provenance-only payload', async () => {
server.use(http.post(`${BASE}/places/from-trip`, record({ duplicate: true, duplicateOf: { id: 9, name: 'Shibuya' } })))
const res = await collectionsApi.saveFromTrip({ collection_id: 1, source_trip_id: 7, source_place_id: 42 })
expect(requestBody).toEqual({ collection_id: 1, source_trip_id: 7, source_place_id: 42 })
expect(res.duplicate).toBe(true)
})
it('FE-API-COLLECTIONS-010: saveFromTripMany() maps its arguments onto the bulk payload', async () => {
server.use(http.post(`${BASE}/places/from-trip-many`, record({ copied: 2, skipped: [] })))
const res = await collectionsApi.saveFromTripMany(1, 7, [11, 12], true)
expect(requestBody).toEqual({ collection_id: 1, source_trip_id: 7, source_place_ids: [11, 12], force: true })
expect(res.copied).toBe(2)
})
it('FE-API-COLLECTIONS-011: updatePlace() patches the place and returns it unwrapped', async () => {
server.use(http.patch(`${BASE}/places/:pid`, record({ ...place, notes: 'busy at night' })))
const res = await collectionsApi.updatePlace(10, { notes: 'busy at night' })
expect(requestUrl).toContain(`${BASE}/places/10`)
expect(requestBody).toEqual({ notes: 'busy at night' })
expect(res.notes).toBe('busy at night')
})
it('FE-API-COLLECTIONS-012: uploadPlaceImage() posts multipart to the place image endpoint', async () => {
server.use(http.post(`${BASE}/places/:pid/image`, record({ ...place, image_url: '/uploads/p.jpg' })))
const fd = new FormData()
fd.append('image', new File(['x'], 'p.jpg'))
const res = await collectionsApi.uploadPlaceImage(10, fd)
expect(requestUrl).toContain(`${BASE}/places/10/image`)
expect(res.image_url).toBe('/uploads/p.jpg')
})
it('FE-API-COLLECTIONS-013: setStatus() posts the status', async () => {
server.use(http.post(`${BASE}/places/:pid/status`, record({ ...place, status: 'visited' })))
const res = await collectionsApi.setStatus(10, 'visited')
expect(requestUrl).toContain(`${BASE}/places/10/status`)
expect(requestBody).toEqual({ status: 'visited' })
expect(res.status).toBe('visited')
})
it('FE-API-COLLECTIONS-014: ratePlace() PUTs a numeric rating', async () => {
server.use(http.put(`${BASE}/places/:pid/rating`, record({ ...place, rating_avg: 4 })))
const res = await collectionsApi.ratePlace(10, 4)
expect(requestUrl).toContain(`${BASE}/places/10/rating`)
expect(requestBody).toEqual({ rating: 4 })
expect(res.rating_avg).toBe(4)
})
it('FE-API-COLLECTIONS-015: ratePlace(null) DELETEs the rating instead', async () => {
let deleted = false
server.use(
http.put(`${BASE}/places/:pid/rating`, () => HttpResponse.json({ error: 'should not be called' }, { status: 500 })),
http.delete(`${BASE}/places/:pid/rating`, () => {
deleted = true
return HttpResponse.json({ ...place, rating_avg: null })
}),
)
const res = await collectionsApi.ratePlace(10, null)
expect(deleted).toBe(true)
expect(res.rating_avg).toBeNull()
})
it('FE-API-COLLECTIONS-016: deletePlace() deletes the saved place', async () => {
server.use(http.delete(`${BASE}/places/:pid`, record({ success: true })))
await collectionsApi.deletePlace(10)
expect(requestUrl).toContain(`${BASE}/places/10`)
})
it('FE-API-COLLECTIONS-017: deleteMany() posts the id list', async () => {
server.use(http.post(`${BASE}/places/delete-many`, record({ deleted: 2 })))
const res = await collectionsApi.deleteMany([10, 11])
expect(requestBody).toEqual({ ids: [10, 11] })
expect(res).toEqual({ deleted: 2 })
})
it('FE-API-COLLECTIONS-018: copyToTrip() posts the copy payload and returns the dedup report', async () => {
server.use(http.post(`${BASE}/copy-to-trip`, record({ copied: 1, skipped: [{ id: 11, name: 'Shibuya' }] })))
const res = await collectionsApi.copyToTrip({ trip_id: 7, place_ids: [10, 11] })
expect(requestBody).toEqual({ trip_id: 7, place_ids: [10, 11] })
expect(res.copied).toBe(1)
expect(res.skipped).toEqual([{ id: 11, name: 'Shibuya' }])
})
it('FE-API-COLLECTIONS-019: membership() sends the lookup as query params', async () => {
server.use(http.get(`${BASE}/membership`, record({ saved: true, lists: [{ collection_id: 1, name: 'Tokyo', place_id: 10 }] })))
const res = await collectionsApi.membership({ google_place_id: 'g1', lat: 35.6, lng: 139.7 })
const params = new URL(requestUrl).searchParams
expect(params.get('google_place_id')).toBe('g1')
expect(params.get('lat')).toBe('35.6')
expect(params.get('lng')).toBe('139.7')
expect(res.saved).toBe(true)
})
it('FE-API-COLLECTIONS-020: invite() posts collection_id, user_id and role', async () => {
server.use(http.post(`${BASE}/invite`, record({ success: true })))
await collectionsApi.invite(1, 5, 'admin')
expect(requestBody).toEqual({ collection_id: 1, user_id: 5, role: 'admin' })
})
it('FE-API-COLLECTIONS-021: setMemberRole() posts the new role', async () => {
server.use(http.post(`${BASE}/members/role`, record({ success: true })))
await collectionsApi.setMemberRole(1, 5, 'viewer')
expect(requestBody).toEqual({ collection_id: 1, user_id: 5, role: 'viewer' })
})
it('FE-API-COLLECTIONS-022: acceptInvite() posts only the collection id', async () => {
server.use(http.post(`${BASE}/invite/accept`, record({ success: true })))
await collectionsApi.acceptInvite(1)
expect(requestBody).toEqual({ collection_id: 1 })
})
it('FE-API-COLLECTIONS-023: declineInvite() posts only the collection id', async () => {
server.use(http.post(`${BASE}/invite/decline`, record({ success: true })))
await collectionsApi.declineInvite(2)
expect(requestBody).toEqual({ collection_id: 2 })
})
it('FE-API-COLLECTIONS-024: cancelInvite() posts collection_id and user_id', async () => {
server.use(http.post(`${BASE}/invite/cancel`, record({ success: true })))
await collectionsApi.cancelInvite(1, 5)
expect(requestBody).toEqual({ collection_id: 1, user_id: 5 })
})
it('FE-API-COLLECTIONS-025: leave() posts the collection id', async () => {
server.use(http.post(`${BASE}/leave`, record({ success: true })))
await collectionsApi.leave(3)
expect(requestBody).toEqual({ collection_id: 3 })
})
it('FE-API-COLLECTIONS-026: removeMember() posts collection_id and user_id', async () => {
server.use(http.post(`${BASE}/members/remove`, record({ success: true })))
await collectionsApi.removeMember(1, 9)
expect(requestBody).toEqual({ collection_id: 1, user_id: 9 })
})
it('FE-API-COLLECTIONS-027: availableUsers() reads the invitable users for a list', async () => {
server.use(http.get(`${BASE}/:id/available-users`, record({ users: [{ id: 5, username: 'bob' }] })))
const res = await collectionsApi.availableUsers(1)
expect(requestUrl).toContain(`${BASE}/1/available-users`)
expect(res.users).toEqual([{ id: 5, username: 'bob' }])
})
it('FE-API-COLLECTIONS-028: createLabel() posts collection_id, name and color', async () => {
server.use(http.post(`${BASE}/labels`, record(label)))
const res = await collectionsApi.createLabel(1, 'Food', '#ef4444')
expect(requestBody).toEqual({ collection_id: 1, name: 'Food', color: '#ef4444' })
expect(res).toEqual(label)
})
it('FE-API-COLLECTIONS-029: updateLabel() patches the label by id', async () => {
server.use(http.patch(`${BASE}/labels/:id`, record({ ...label, name: 'Eats' })))
const res = await collectionsApi.updateLabel(3, { name: 'Eats' })
expect(requestUrl).toContain(`${BASE}/labels/3`)
expect(requestBody).toEqual({ name: 'Eats' })
expect(res.name).toBe('Eats')
})
it('FE-API-COLLECTIONS-030: deleteLabel() deletes the label by id', async () => {
server.use(http.delete(`${BASE}/labels/:id`, record({ success: true })))
await collectionsApi.deleteLabel(3)
expect(requestUrl).toContain(`${BASE}/labels/3`)
})
it('FE-API-COLLECTIONS-031: assignLabels() posts label_ids and place_ids', async () => {
server.use(http.post(`${BASE}/labels/assign`, record({ changed: 2 })))
const res = await collectionsApi.assignLabels([3], [10, 11])
expect(requestBody).toEqual({ label_ids: [3], place_ids: [10, 11] })
expect(res.changed).toBe(2)
})
it('FE-API-COLLECTIONS-032: unassignLabels() posts to the unassign endpoint', async () => {
server.use(http.post(`${BASE}/labels/unassign`, record({ changed: 1 })))
const res = await collectionsApi.unassignLabels([3], [10])
expect(requestUrl).toContain(`${BASE}/labels/unassign`)
expect(requestBody).toEqual({ label_ids: [3], place_ids: [10] })
expect(res.changed).toBe(1)
})
})
+267
View File
@@ -0,0 +1,267 @@
// vi.unmock must run before the module is imported (tests/setup.ts mocks it globally)
vi.unmock('./websocket')
// FE-WSCORE-001 to FE-WSCORE-014
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import {
connect, disconnect, joinTrip, leaveTrip, getActiveTrips,
setRefetchCallback, setPreReconnectHook,
} from './websocket'
class MockWebSocket {
static CONNECTING = 0
static OPEN = 1
static CLOSING = 2
static CLOSED = 3
static instances: MockWebSocket[] = []
readyState: number = MockWebSocket.OPEN
send = vi.fn((_data: string) => {})
close = vi.fn(() => {})
onopen: (() => void) | null = null
onmessage: ((event: { data: string }) => void) | null = null
onclose: (() => void) | null = null
onerror: (() => void) | null = null
constructor(public url: string) {
MockWebSocket.instances.push(this)
}
}
function lastSocket(): MockWebSocket {
return MockWebSocket.instances[MockWebSocket.instances.length - 1]
}
const realLocation = window.location
beforeEach(() => {
vi.useFakeTimers()
MockWebSocket.instances = []
Object.defineProperty(globalThis, 'WebSocket', {
writable: true, configurable: true, value: MockWebSocket,
})
server.use(http.post('/api/auth/ws-token', () => HttpResponse.json({ token: 'ws-tok' })))
})
afterEach(() => {
disconnect()
setRefetchCallback(null)
setPreReconnectHook(null)
vi.useRealTimers()
vi.restoreAllMocks()
Object.defineProperty(window, 'location', { writable: true, configurable: true, value: realLocation })
})
/** connect() + settle the token fetch so a socket exists. */
async function openSocket(): Promise<MockWebSocket> {
connect()
await vi.advanceTimersByTimeAsync(0)
return lastSocket()
}
describe('websocket > active trips', () => {
it('FE-WSCORE-001: getActiveTrips lists the joined trips as strings', async () => {
expect(getActiveTrips()).toEqual([])
joinTrip(42)
joinTrip('7')
expect(getActiveTrips()).toEqual(['42', '7'])
disconnect()
expect(getActiveTrips()).toEqual([])
})
it('FE-WSCORE-013: join/leave still bookkeep while no socket is open', () => {
joinTrip(5)
expect(getActiveTrips()).toEqual(['5'])
leaveTrip(5)
expect(getActiveTrips()).toEqual([])
})
it('FE-WSCORE-014: a trip joined before onopen is not re-sent while the socket is closing', async () => {
joinTrip(11)
const sock = await openSocket()
sock.readyState = MockWebSocket.CLOSING
sock.onopen!()
expect(sock.send).not.toHaveBeenCalled()
})
})
describe('websocket > reconnect refetch hook', () => {
it('FE-WSCORE-002: the pre-reconnect hook is awaited before the refetch runs', async () => {
const order: string[] = []
setPreReconnectHook(async () => { order.push('flush') })
setRefetchCallback(() => { order.push('refetch') })
joinTrip(3)
const sock = await openSocket()
sock.onopen!()
await vi.advanceTimersByTimeAsync(0)
expect(order).toEqual(['flush', 'refetch'])
})
it('FE-WSCORE-003: a rejecting pre-reconnect hook still lets the refetch run', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
const refetch = vi.fn((_tripId: string) => {})
setPreReconnectHook(async () => { throw new Error('queue flush failed') })
setRefetchCallback(refetch)
joinTrip(3)
const sock = await openSocket()
sock.onopen!()
await vi.advanceTimersByTimeAsync(0)
expect(refetch).toHaveBeenCalledWith('3')
expect(consoleError).toHaveBeenCalled()
})
it('FE-WSCORE-004: a throwing refetch callback is logged, not propagated', async () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
setRefetchCallback(() => { throw new Error('store blew up') })
joinTrip(3)
const sock = await openSocket()
expect(() => sock.onopen!()).not.toThrow()
expect(consoleError).toHaveBeenCalledWith(
'Failed to refetch trip data on reconnect:',
expect.any(Error),
)
})
it('FE-WSCORE-005: with no joined trips onopen sends nothing and skips the refetch', async () => {
const refetch = vi.fn((_tripId: string) => {})
setRefetchCallback(refetch)
const sock = await openSocket()
sock.onopen!()
expect(sock.send).not.toHaveBeenCalled()
expect(refetch).not.toHaveBeenCalled()
})
})
describe('websocket > connection lifecycle', () => {
it('FE-WSCORE-006: connect() is a no-op while a socket is still CONNECTING', async () => {
const sock = await openSocket()
sock.readyState = MockWebSocket.CONNECTING
connect()
await vi.advanceTimersByTimeAsync(0)
expect(MockWebSocket.instances).toHaveLength(1)
})
it('FE-WSCORE-007: connect() cancels a pending reconnect timer', async () => {
server.use(http.post('/api/auth/ws-token', () => new HttpResponse(null, { status: 503 })))
connect()
await vi.advanceTimersByTimeAsync(0)
expect(MockWebSocket.instances).toHaveLength(0)
// A retry is now armed; connect() must clear it and dial immediately.
server.use(http.post('/api/auth/ws-token', () => HttpResponse.json({ token: 'fresh' })))
connect()
await vi.advanceTimersByTimeAsync(0)
expect(MockWebSocket.instances).toHaveLength(1)
// The cancelled timer must not fire a second dial afterwards.
await vi.advanceTimersByTimeAsync(5000)
expect(MockWebSocket.instances).toHaveLength(1)
})
it('FE-WSCORE-008: a duplicate close does not stack a second timer or skip a backoff step', async () => {
const sock = await openSocket()
// Every further token fetch fails, so each retry attempt is countable.
let attempts = 0
server.use(http.post('/api/auth/ws-token', () => {
attempts++
return new HttpResponse(null, { status: 503 })
}))
// A browser can deliver close twice (after onerror); the second must be ignored.
sock.onclose!()
sock.onclose!()
await vi.advanceTimersByTimeAsync(1001)
await vi.advanceTimersByTimeAsync(0)
expect(attempts, 'first retry fires after the 1s delay').toBe(1)
// Backoff advanced once (1s → 2s), not twice, so the next retry lands at 2s.
await vi.advanceTimersByTimeAsync(2001)
await vi.advanceTimersByTimeAsync(0)
expect(attempts, 'second retry fires after the doubled 2s delay').toBe(2)
expect(MockWebSocket.instances).toHaveLength(1)
})
it('FE-WSCORE-009: a failing ws-token fetch schedules a retry instead of throwing', async () => {
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new TypeError('offline'))
connect()
await vi.advanceTimersByTimeAsync(0)
expect(MockWebSocket.instances).toHaveLength(0)
vi.mocked(globalThis.fetch).mockResolvedValue(
new Response(JSON.stringify({ token: 'back-online' }), {
status: 200, headers: { 'Content-Type': 'application/json' },
}),
)
await vi.advanceTimersByTimeAsync(1001)
await vi.advanceTimersByTimeAsync(0)
expect(MockWebSocket.instances).toHaveLength(1)
expect(lastSocket().url).toContain('token=back-online')
})
it('FE-WSCORE-010: the socket URL uses ws:// on http and wss:// on https', async () => {
const httpSock = await openSocket()
expect(httpSock.url.startsWith('ws://')).toBe(true)
disconnect()
MockWebSocket.instances = []
Object.defineProperty(window, 'location', {
writable: true, configurable: true,
value: {
protocol: 'https:',
host: 'trip.example',
origin: 'https://trip.example',
href: 'https://trip.example/dashboard',
pathname: '/dashboard',
},
})
const secure = await openSocket()
expect(secure.url).toBe('wss://trip.example/ws?token=ws-tok')
})
it('FE-WSCORE-011: disconnect() detaches onclose so no reconnect is armed', async () => {
const sock = await openSocket()
disconnect()
expect(sock.onclose).toBeNull()
expect(sock.close).toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(5000)
expect(MockWebSocket.instances).toHaveLength(1)
})
it('FE-WSCORE-012: onerror is inert — the reconnect is driven by onclose', async () => {
const sock = await openSocket()
expect(() => sock.onerror!()).not.toThrow()
expect(MockWebSocket.instances).toHaveLength(1)
sock.onclose!()
await vi.advanceTimersByTimeAsync(1001)
await vi.advanceTimersByTimeAsync(0)
expect(MockWebSocket.instances).toHaveLength(2)
})
})
+402
View File
@@ -0,0 +1,402 @@
// FE-DB-OFFLINE-001 to FE-DB-OFFLINE-029
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import Dexie from 'dexie'
import {
offlineDb,
clearAll,
clearTripData,
reopenForUser,
reopenAnonymous,
deleteCurrentUserDb,
upsertTrip,
upsertDays,
upsertPlaces,
upsertPackingItems,
upsertTodoItems,
upsertBudgetItems,
upsertReservations,
upsertTripFiles,
upsertAccommodations,
upsertTripMembers,
upsertTags,
upsertCategories,
upsertSyncMeta,
getCachedBlob,
saveImportFiles,
getImportFiles,
deleteImportFiles,
enforceBlobBudget,
BLOB_CACHE_MAX_ENTRIES,
BLOB_CACHE_MAX_BYTES,
} from './offlineDb'
import type { BlobCacheEntry, QueuedMutation } from './offlineDb'
import type { Accommodation, TripMember } from '../types'
import {
buildTrip,
buildDay,
buildPlace,
buildPackingItem,
buildTodoItem,
buildBudgetItem,
buildReservation,
buildTripFile,
buildTag,
buildCategory,
} from '../../tests/helpers/factories'
function blobEntry(url: string, cachedAt: number, bytes: number, tripId = 1): BlobCacheEntry {
return { url, tripId, blob: new Blob(['x'.repeat(bytes)]), bytes, mime: 'application/pdf', cachedAt }
}
function queued(id: string, tripId: number, status: QueuedMutation['status']): QueuedMutation {
return { id, tripId, method: 'PUT', url: `/trips/${tripId}/places/1`, body: {}, createdAt: 1, status, attempts: 0, lastError: null }
}
beforeEach(async () => {
await clearAll()
})
afterEach(async () => {
vi.restoreAllMocks()
await reopenAnonymous()
})
describe('offlineDb — bulk upsert helpers', () => {
it('FE-DB-OFFLINE-001: every entity helper writes into its own table', async () => {
await upsertTrip(buildTrip({ id: 1 }))
await upsertDays([buildDay({ id: 1, trip_id: 1 })])
await upsertPlaces([buildPlace({ id: 1, trip_id: 1 })])
await upsertPackingItems([buildPackingItem({ id: 1, trip_id: 1 })])
await upsertTodoItems([buildTodoItem({ id: 1, trip_id: 1 })])
await upsertBudgetItems([buildBudgetItem({ id: 1, trip_id: 1 })])
await upsertReservations([buildReservation({ id: 1, trip_id: 1 })])
await upsertTripFiles([buildTripFile({ id: 1, trip_id: 1 })])
await upsertAccommodations([{ id: 1, trip_id: 1, start_day_id: 1, end_day_id: 2 } as Accommodation])
await upsertTags([buildTag({ id: 1 })])
await upsertCategories([buildCategory({ id: 1 })])
expect(await offlineDb.trips.count()).toBe(1)
expect(await offlineDb.days.count()).toBe(1)
expect(await offlineDb.places.count()).toBe(1)
expect(await offlineDb.packingItems.count()).toBe(1)
expect(await offlineDb.todoItems.count()).toBe(1)
expect(await offlineDb.budgetItems.count()).toBe(1)
expect(await offlineDb.reservations.count()).toBe(1)
expect(await offlineDb.tripFiles.count()).toBe(1)
expect(await offlineDb.accommodations.count()).toBe(1)
expect(await offlineDb.tags.count()).toBe(1)
expect(await offlineDb.categories.count()).toBe(1)
})
it('FE-DB-OFFLINE-002: upsertTripMembers stamps the tripId onto every member row', async () => {
const members = [
{ id: 5, username: 'ana', role: 'owner' },
{ id: 6, username: 'ben', role: 'member' },
] as unknown as TripMember[]
await upsertTripMembers(42, members)
const rows = await offlineDb.tripMembers.where('tripId').equals(42).toArray()
expect(rows.map(r => r.username).sort()).toEqual(['ana', 'ben'])
expect(rows.every(r => r.tripId === 42)).toBe(true)
})
it('FE-DB-OFFLINE-003: upsertSyncMeta overwrites the previous row for the same trip', async () => {
await upsertSyncMeta({ tripId: 1, lastSyncedAt: 100, status: 'idle', tilesBbox: null, filesCachedCount: 0 })
await upsertSyncMeta({ tripId: 1, lastSyncedAt: 200, status: 'error', tilesBbox: [0, 0, 1, 1], filesCachedCount: 3 })
const meta = await offlineDb.syncMeta.get(1)
expect(meta).toMatchObject({ lastSyncedAt: 200, status: 'error', filesCachedCount: 3 })
expect(await offlineDb.syncMeta.count()).toBe(1)
})
})
describe('offlineDb — getCachedBlob', () => {
it('FE-DB-OFFLINE-004: returns null when the url was never cached', async () => {
expect(await getCachedBlob('/api/files/1/download')).toBeNull()
})
it('FE-DB-OFFLINE-005: reapplies the stored MIME when the persisted Blob lost its type', async () => {
await offlineDb.blobCache.put({
url: '/a.csv', tripId: 1, blob: new Blob(['a,b']), bytes: 3, mime: 'text/csv', cachedAt: 1,
})
const blob = await getCachedBlob('/a.csv')
expect(blob).toBeInstanceOf(Blob)
expect(blob!.type).toBe('text/csv')
})
it('FE-DB-OFFLINE-006: falls back to octet-stream when neither the Blob nor the row has a type', async () => {
await offlineDb.blobCache.put({
url: '/a.bin', tripId: 1, blob: new Blob(['a']), bytes: 1, mime: '', cachedAt: 1,
})
expect((await getCachedBlob('/a.bin'))!.type).toBe('application/octet-stream')
})
it('FE-DB-OFFLINE-007: a read error degrades to null instead of throwing', async () => {
vi.spyOn(offlineDb.blobCache, 'get').mockRejectedValue(new Error('db closed'))
expect(await getCachedBlob('/a.pdf')).toBeNull()
})
})
describe('offlineDb — booking-import source files', () => {
it('FE-DB-OFFLINE-008: stores a job\'s files under [jobId+fileName] and rebuilds them as Files', async () => {
await saveImportFiles('job-1', [
new File(['a'], 'ticket.pdf', { type: 'application/pdf' }),
new File(['b'], 'boarding.pdf', { type: 'application/pdf' }),
])
expect(await offlineDb.importFiles.where('jobId').equals('job-1').count()).toBe(2)
const files = await getImportFiles('job-1')
expect(files.map(f => f.name).sort()).toEqual(['boarding.pdf', 'ticket.pdf'])
expect(files.every(f => f instanceof File)).toBe(true)
})
it('FE-DB-OFFLINE-009: a stored Blob without a type is rebuilt as octet-stream', async () => {
await saveImportFiles('job-2', [new File(['x'], 'unknown')])
expect((await getImportFiles('job-2'))[0].type).toBe('application/octet-stream')
})
it('FE-DB-OFFLINE-010: saving prunes source files from abandoned imports older than an hour', async () => {
await offlineDb.importFiles.put({
jobId: 'stale', fileName: 'old.pdf', blob: new Blob(['old']), createdAt: Date.now() - 2 * 3600_000,
})
await saveImportFiles('fresh', [new File(['new'], 'new.pdf')])
expect(await getImportFiles('stale')).toEqual([])
expect(await getImportFiles('fresh')).toHaveLength(1)
})
it('FE-DB-OFFLINE-011: deleteImportFiles drops only the given job', async () => {
await saveImportFiles('job-a', [new File(['a'], 'a.pdf')])
await saveImportFiles('job-b', [new File(['b'], 'b.pdf')])
await deleteImportFiles('job-a')
expect(await getImportFiles('job-a')).toEqual([])
expect(await getImportFiles('job-b')).toHaveLength(1)
})
it('FE-DB-OFFLINE-012: all three helpers stay best-effort when Dexie throws', async () => {
vi.spyOn(offlineDb.importFiles, 'bulkPut').mockRejectedValue(new Error('quota'))
vi.spyOn(offlineDb.importFiles, 'where').mockImplementation(() => { throw new Error('db closed') })
await expect(saveImportFiles('job-c', [new File(['c'], 'c.pdf')])).resolves.toBeUndefined()
await expect(getImportFiles('job-c')).resolves.toEqual([])
await expect(deleteImportFiles('job-c')).resolves.toBeUndefined()
})
})
describe('offlineDb — blob cache budget', () => {
it('FE-DB-OFFLINE-013: exposes conservative defaults', () => {
expect(BLOB_CACHE_MAX_ENTRIES).toBe(200)
expect(BLOB_CACHE_MAX_BYTES).toBe(100 * 1024 * 1024)
})
it('FE-DB-OFFLINE-014: a cache within both budgets is left untouched', async () => {
await offlineDb.blobCache.bulkPut([blobEntry('/1', 1, 10), blobEntry('/2', 2, 10)])
await enforceBlobBudget(5, 1000)
expect(await offlineDb.blobCache.count()).toBe(2)
})
it('FE-DB-OFFLINE-015: evicts oldest-first until the entry count fits', async () => {
await offlineDb.blobCache.bulkPut([blobEntry('/1', 1, 10), blobEntry('/2', 2, 10), blobEntry('/3', 3, 10)])
await enforceBlobBudget(1, 1000)
expect((await offlineDb.blobCache.toArray()).map(e => e.url)).toEqual(['/3'])
})
it('FE-DB-OFFLINE-016: evicts oldest-first until the byte budget fits', async () => {
await offlineDb.blobCache.bulkPut([blobEntry('/1', 1, 100), blobEntry('/2', 2, 100), blobEntry('/3', 3, 100)])
await enforceBlobBudget(100, 150)
expect((await offlineDb.blobCache.toArray()).map(e => e.url)).toEqual(['/3'])
})
it('FE-DB-OFFLINE-017: rows written before the bytes column are counted as zero', async () => {
await offlineDb.blobCache.bulkPut([
{ url: '/legacy', tripId: -1, blob: new Blob(['x']), mime: '', cachedAt: 1 } as unknown as BlobCacheEntry,
blobEntry('/2', 2, 100),
])
await enforceBlobBudget(100, 100)
expect(await offlineDb.blobCache.count()).toBe(2)
})
})
describe('offlineDb — clearTripData', () => {
it('FE-DB-OFFLINE-018: drops the trip\'s read cache and leaves other trips alone', async () => {
await upsertTrip(buildTrip({ id: 1 }))
await upsertTrip(buildTrip({ id: 2 }))
await upsertDays([buildDay({ id: 1, trip_id: 1 }), buildDay({ id: 2, trip_id: 2 })])
await upsertPlaces([buildPlace({ id: 1, trip_id: 1 }), buildPlace({ id: 2, trip_id: 2 })])
await upsertPackingItems([buildPackingItem({ id: 1, trip_id: 1 })])
await upsertTodoItems([buildTodoItem({ id: 1, trip_id: 1 })])
await upsertBudgetItems([buildBudgetItem({ id: 1, trip_id: 1 })])
await upsertReservations([buildReservation({ id: 1, trip_id: 1 })])
await upsertTripFiles([buildTripFile({ id: 1, trip_id: 1 })])
await upsertAccommodations([{ id: 1, trip_id: 1, start_day_id: 1, end_day_id: 2 } as Accommodation])
await upsertTripMembers(1, [{ id: 9, username: 'ana', role: 'owner' } as unknown as TripMember])
await upsertSyncMeta({ tripId: 1, lastSyncedAt: 1, status: 'idle', tilesBbox: null, filesCachedCount: 0 })
await offlineDb.blobCache.put(blobEntry('/f1', 1, 10, 1))
await offlineDb.blobCache.put(blobEntry('/f2', 2, 10, 2))
await clearTripData(1)
expect(await offlineDb.trips.get(1)).toBeUndefined()
expect(await offlineDb.days.where('trip_id').equals(1).count()).toBe(0)
expect(await offlineDb.places.where('trip_id').equals(1).count()).toBe(0)
expect(await offlineDb.packingItems.count()).toBe(0)
expect(await offlineDb.todoItems.count()).toBe(0)
expect(await offlineDb.budgetItems.count()).toBe(0)
expect(await offlineDb.reservations.count()).toBe(0)
expect(await offlineDb.tripFiles.count()).toBe(0)
expect(await offlineDb.accommodations.count()).toBe(0)
expect(await offlineDb.tripMembers.count()).toBe(0)
expect(await offlineDb.syncMeta.get(1)).toBeUndefined()
expect(await offlineDb.trips.get(2)).toBeDefined()
expect(await offlineDb.days.where('trip_id').equals(2).count()).toBe(1)
expect((await offlineDb.blobCache.toArray()).map(e => e.url)).toEqual(['/f2'])
})
it('FE-DB-OFFLINE-019: keeps unsynced work and only purges dead failed mutations', async () => {
await offlineDb.mutationQueue.bulkPut([
queued('m-pending', 1, 'pending'),
queued('m-syncing', 1, 'syncing'),
queued('m-conflict', 1, 'conflict'),
queued('m-failed', 1, 'failed'),
queued('m-other-trip', 2, 'failed'),
])
await clearTripData(1)
const left = (await offlineDb.mutationQueue.toArray()).map(m => m.id).sort()
expect(left).toEqual(['m-conflict', 'm-other-trip', 'm-pending', 'm-syncing'])
})
})
describe('offlineDb — per-user database scoping', () => {
it('FE-DB-OFFLINE-020: reopenForUser switches to the user-scoped database', async () => {
await reopenForUser(7)
expect(offlineDb.name).toBe('trek-offline-u7')
expect(offlineDb.isOpen()).toBe(true)
})
it('FE-DB-OFFLINE-021: one account cannot read another account\'s cached trips', async () => {
await reopenForUser(7)
await upsertTrip(buildTrip({ id: 500, title: 'Seven' }))
await reopenForUser(8)
expect(await offlineDb.trips.get(500)).toBeUndefined()
await reopenForUser(7)
expect((await offlineDb.trips.get(500))!.title).toBe('Seven')
})
it('FE-DB-OFFLINE-022: switching to the database already in use just reopens it', async () => {
await reopenForUser(7)
offlineDb.close()
await reopenForUser(7)
expect(offlineDb.name).toBe('trek-offline-u7')
expect(offlineDb.isOpen()).toBe(true)
})
it('FE-DB-OFFLINE-023: deleteCurrentUserDb wipes the account data and returns to anonymous', async () => {
await reopenForUser(9)
await upsertTrip(buildTrip({ id: 501 }))
await deleteCurrentUserDb()
expect(offlineDb.name).toBe('trek-offline')
await reopenForUser(9)
expect(await offlineDb.trips.count()).toBe(0)
})
it('FE-DB-OFFLINE-024: deleteCurrentUserDb on the anonymous database is a no-op switch', async () => {
await reopenAnonymous()
await upsertTrip(buildTrip({ id: 502 }))
await deleteCurrentUserDb()
expect(offlineDb.name).toBe('trek-offline')
expect(await offlineDb.trips.get(502)).toBeDefined()
})
})
describe('offlineDb — connection proxy', () => {
it('FE-DB-OFFLINE-028: reads and writes go to the connection that is live right now', async () => {
const proxied = offlineDb as unknown as Record<string, unknown>
proxied.__marker = 'anon'
expect(proxied.__marker).toBe('anon')
await reopenForUser(56)
expect((offlineDb as unknown as Record<string, unknown>).__marker).toBeUndefined()
})
it('FE-DB-OFFLINE-029: upgrading a pre-v3 cache backfills tripId and bytes on blob rows', async () => {
const legacy = new Dexie('trek-offline-u55')
legacy.version(1).stores({
trips: 'id',
days: 'id, trip_id',
places: 'id, trip_id',
packingItems: 'id, trip_id',
todoItems: 'id, trip_id',
budgetItems: 'id, trip_id',
reservations: 'id, trip_id',
tripFiles: 'id, trip_id',
mutationQueue: 'id, tripId, status, createdAt',
syncMeta: 'tripId',
blobCache: 'url, cachedAt',
})
legacy.version(2).stores({
accommodations: 'id, trip_id',
tripMembers: '[tripId+id], tripId',
tags: 'id',
categories: 'id',
})
await legacy.open()
await legacy.table('blobCache').put({ url: '/legacy.pdf', blob: new Blob(['abc']), mime: 'application/pdf', cachedAt: 1 })
legacy.close()
await reopenForUser(55)
const row = await offlineDb.blobCache.get('/legacy.pdf')
expect(row!.tripId).toBe(-1)
expect(typeof row!.bytes).toBe('number')
})
})
describe('offlineDb — initial database name', () => {
it('FE-DB-OFFLINE-025: boots straight into the persisted user\'s database', async () => {
localStorage.setItem('trek_auth_snapshot', JSON.stringify({ state: { user: { id: 33 } } }))
vi.resetModules()
const mod = await import('./offlineDb')
expect(mod.offlineDb.name).toBe('trek-offline-u33')
})
it('FE-DB-OFFLINE-026: falls back to the anonymous database without a snapshot', async () => {
localStorage.removeItem('trek_auth_snapshot')
vi.resetModules()
const mod = await import('./offlineDb')
expect(mod.offlineDb.name).toBe('trek-offline')
})
it('FE-DB-OFFLINE-027: a corrupt snapshot falls back to the anonymous database', async () => {
localStorage.setItem('trek_auth_snapshot', 'not json')
vi.resetModules()
const mod = await import('./offlineDb')
expect(mod.offlineDb.name).toBe('trek-offline')
})
})
+118
View File
@@ -0,0 +1,118 @@
// FE-HOOK-COUNTUP-001 to FE-HOOK-COUNTUP-006
import { act, renderHook } from '@testing-library/react';
// The hook reads navigator.userAgent once at module load to detect jsdom and
// skip the animation. Every test therefore imports it fresh, with the user
// agent already faked to whatever that test needs.
async function loadHook(userAgent: string) {
vi.resetModules();
Object.defineProperty(navigator, 'userAgent', { value: userAgent, configurable: true });
return (await import('./useCountUp')).useCountUp;
}
const BROWSER_UA = 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 Chrome/131.0.0.0';
const JSDOM_UA = 'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 jsdom/26.0.0';
/** Drives requestAnimationFrame by hand so the easing is deterministic. */
function stubRaf(): { flush: (now: number) => void; cancelled: number[] } {
const pending = new Map<number, FrameRequestCallback>();
const cancelled: number[] = [];
let id = 0;
vi.stubGlobal('requestAnimationFrame', vi.fn((cb: FrameRequestCallback) => {
pending.set(++id, cb);
return id;
}));
vi.stubGlobal('cancelAnimationFrame', vi.fn((handle: number) => {
cancelled.push(handle);
pending.delete(handle);
}));
return {
flush(now: number) {
const due = [...pending.entries()];
pending.clear();
for (const [, cb] of due) cb(now);
},
cancelled,
};
}
afterEach(() => {
vi.unstubAllGlobals();
Object.defineProperty(navigator, 'userAgent', { value: JSDOM_UA, configurable: true });
});
describe('useCountUp', () => {
it('FE-HOOK-COUNTUP-001: returns the target immediately under jsdom', async () => {
const useCountUp = await loadHook(JSDOM_UA);
const { result } = renderHook(() => useCountUp(42));
expect(result.current).toBe(42);
});
it('FE-HOOK-COUNTUP-002: animates from 0 to the target with an ease-out curve', async () => {
const raf = stubRaf();
const useCountUp = await loadHook(BROWSER_UA);
const { result } = renderHook(() => useCountUp(100, 1000));
expect(result.current).toBe(0);
// First frame establishes the start timestamp, so it still reads 0.
act(() => raf.flush(1000));
expect(result.current).toBe(0);
// Half way through, ease-out-quint is already at 1 - 0.5^5 = 96.875%.
act(() => raf.flush(1500));
expect(result.current).toBe(97);
act(() => raf.flush(2000));
expect(result.current).toBe(100);
});
it('FE-HOOK-COUNTUP-003: stops requesting frames once it reaches the target', async () => {
const raf = stubRaf();
const useCountUp = await loadHook(BROWSER_UA);
const { result } = renderHook(() => useCountUp(50, 400));
act(() => raf.flush(0));
act(() => raf.flush(400));
expect(result.current).toBe(50);
// No further frame was scheduled, so flushing again changes nothing.
act(() => raf.flush(800));
expect(result.current).toBe(50);
});
it('FE-HOOK-COUNTUP-004: cancels the pending frame on unmount', async () => {
const raf = stubRaf();
const useCountUp = await loadHook(BROWSER_UA);
const { unmount } = renderHook(() => useCountUp(80, 600));
act(() => raf.flush(0));
unmount();
expect(raf.cancelled.length).toBeGreaterThan(0);
});
it('FE-HOOK-COUNTUP-005: skips the animation when reduced motion is preferred', async () => {
stubRaf();
const useCountUp = await loadHook(BROWSER_UA);
const matchMedia = vi.mocked(window.matchMedia);
matchMedia.mockReturnValueOnce({ matches: true } as unknown as MediaQueryList);
const { result } = renderHook(() => useCountUp(64));
expect(result.current).toBe(64);
expect(requestAnimationFrame).not.toHaveBeenCalled();
});
it('FE-HOOK-COUNTUP-006: passes non-positive targets straight through', async () => {
stubRaf();
const useCountUp = await loadHook(BROWSER_UA);
const { result, rerender } = renderHook(({ target }) => useCountUp(target), {
initialProps: { target: 0 },
});
expect(result.current).toBe(0);
rerender({ target: -5 });
expect(result.current).toBe(-5);
expect(requestAnimationFrame).not.toHaveBeenCalled();
});
});
+101
View File
@@ -0,0 +1,101 @@
// FE-HOOK-ELRECT-001 to FE-HOOK-ELRECT-007
import { act, renderHook } from '@testing-library/react';
import { useElementRect } from './useElementRect';
const observers: { fire: () => void; disconnected: boolean }[] = [];
class ControllableResizeObserver {
private entry: { fire: () => void; disconnected: boolean } | null = null;
constructor(private cb: ResizeObserverCallback) {}
observe() {
this.entry = { fire: () => this.cb([], this as unknown as ResizeObserver), disconnected: false };
observers.push(this.entry);
}
unobserve() {}
disconnect() {
if (this.entry) this.entry.disconnected = true;
}
}
function element(left: number, width: number): HTMLElement {
const el = document.createElement('div');
el.getBoundingClientRect = () => ({ left, width, right: left + width, top: 0, bottom: 0, height: 0, x: left, y: 0, toJSON: () => ({}) });
return el;
}
function moveTo(el: HTMLElement, left: number, width: number): void {
el.getBoundingClientRect = () => ({ left, width, right: left + width, top: 0, bottom: 0, height: 0, x: left, y: 0, toJSON: () => ({}) });
}
beforeEach(() => {
observers.length = 0;
vi.stubGlobal('ResizeObserver', ControllableResizeObserver);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('useElementRect', () => {
it('FE-HOOK-ELRECT-001: has no rect until an element is attached', () => {
const { result } = renderHook(() => useElementRect());
expect(result.current.rect).toBeNull();
});
it('FE-HOOK-ELRECT-002: measures left and width on attach', () => {
const { result } = renderHook(() => useElementRect());
act(() => result.current.ref(element(240, 400)));
expect(result.current.rect).toEqual({ left: 240, width: 400 });
});
it('FE-HOOK-ELRECT-003: re-measures when the element resizes', () => {
const { result } = renderHook(() => useElementRect());
const el = element(240, 400);
act(() => result.current.ref(el));
moveTo(el, 120, 560);
act(() => observers[0].fire());
expect(result.current.rect).toEqual({ left: 120, width: 560 });
});
it('FE-HOOK-ELRECT-004: re-measures on a window resize', () => {
const { result } = renderHook(() => useElementRect());
const el = element(240, 400);
act(() => result.current.ref(el));
moveTo(el, 0, 800);
act(() => window.dispatchEvent(new Event('resize')));
expect(result.current.rect).toEqual({ left: 0, width: 800 });
});
it('FE-HOOK-ELRECT-005: keeps the previous rect object when nothing moved', () => {
const { result } = renderHook(() => useElementRect());
act(() => result.current.ref(element(240, 400)));
const before = result.current.rect;
act(() => observers[0].fire());
expect(result.current.rect).toBe(before);
});
it('FE-HOOK-ELRECT-006: clears the rect and disconnects when the ref detaches', () => {
const { result } = renderHook(() => useElementRect());
act(() => result.current.ref(element(240, 400)));
act(() => result.current.ref(null));
expect(result.current.rect).toBeNull();
expect(observers[0].disconnected).toBe(true);
});
it('FE-HOOK-ELRECT-007: drops the window listener on unmount', () => {
const remove = vi.spyOn(window, 'removeEventListener');
const { result, unmount } = renderHook(() => useElementRect());
act(() => result.current.ref(element(10, 20)));
unmount();
expect(remove).toHaveBeenCalledWith('resize', expect.any(Function));
remove.mockRestore();
});
});
+105
View File
@@ -0,0 +1,105 @@
// FE-HOOK-ELSIZE-001 to FE-HOOK-ELSIZE-006
import { act, renderHook } from '@testing-library/react';
import { useElementSize } from './useElementSize';
// tests/setup.ts installs a no-op ResizeObserver. Swap in one that hands the
// callback back so a resize can be simulated, and count the connections so the
// disconnect-on-detach contract is observable.
const observers: { el: Element; fire: () => void; disconnected: boolean }[] = [];
class ControllableResizeObserver {
private entry: { el: Element; fire: () => void; disconnected: boolean } | null = null;
constructor(private cb: ResizeObserverCallback) {}
observe(el: Element) {
this.entry = { el, fire: () => this.cb([], this as unknown as ResizeObserver), disconnected: false };
observers.push(this.entry);
}
unobserve() {}
disconnect() {
if (this.entry) this.entry.disconnected = true;
}
}
function element(width: number, height: number): HTMLElement {
const el = document.createElement('div');
Object.defineProperty(el, 'offsetWidth', { value: width, configurable: true });
Object.defineProperty(el, 'offsetHeight', { value: height, configurable: true });
return el;
}
function resize(el: HTMLElement, width: number, height: number): void {
Object.defineProperty(el, 'offsetWidth', { value: width, configurable: true });
Object.defineProperty(el, 'offsetHeight', { value: height, configurable: true });
}
beforeEach(() => {
observers.length = 0;
vi.stubGlobal('ResizeObserver', ControllableResizeObserver);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('useElementSize', () => {
it('FE-HOOK-ELSIZE-001: starts at zero before an element is attached', () => {
const { result } = renderHook(() => useElementSize());
expect(result.current.width).toBe(0);
expect(result.current.height).toBe(0);
expect(observers).toHaveLength(0);
});
it('FE-HOOK-ELSIZE-002: measures the element as soon as the ref is attached', () => {
const { result } = renderHook(() => useElementSize());
act(() => result.current.ref(element(320, 180)));
expect(result.current.width).toBe(320);
expect(result.current.height).toBe(180);
expect(observers).toHaveLength(1);
});
it('FE-HOOK-ELSIZE-003: picks up a later resize of the same element', () => {
const { result } = renderHook(() => useElementSize());
const el = element(320, 180);
act(() => result.current.ref(el));
resize(el, 640, 400);
act(() => observers[0].fire());
expect(result.current.width).toBe(640);
expect(result.current.height).toBe(400);
});
it('FE-HOOK-ELSIZE-004: keeps the same state object when the size is unchanged', () => {
const { result } = renderHook(() => useElementSize());
act(() => result.current.ref(element(200, 100)));
const before = result.current;
act(() => observers[0].fire());
// No re-render — the hook bailed out of setState because nothing moved.
expect(result.current.width).toBe(before.width);
expect(result.current.height).toBe(before.height);
});
it('FE-HOOK-ELSIZE-005: disconnects the old observer when the ref moves to another element', () => {
const { result } = renderHook(() => useElementSize());
act(() => result.current.ref(element(100, 50)));
act(() => result.current.ref(element(300, 150)));
expect(observers).toHaveLength(2);
expect(observers[0].disconnected).toBe(true);
expect(observers[1].disconnected).toBe(false);
expect(result.current.width).toBe(300);
});
it('FE-HOOK-ELSIZE-006: disconnects when React detaches the ref with null', () => {
const { result } = renderHook(() => useElementSize());
act(() => result.current.ref(element(100, 50)));
act(() => result.current.ref(null));
expect(observers[0].disconnected).toBe(true);
// The last measured size is kept — only the observation stops.
expect(result.current.width).toBe(100);
});
});
+261
View File
@@ -0,0 +1,261 @@
// FE-HOOK-GEO-001 to FE-HOOK-GEO-014
import { act, renderHook } from '@testing-library/react';
import { useGeolocation } from './useGeolocation';
type WatchSuccess = (pos: GeolocationPosition) => void;
type WatchFailure = (err: GeolocationPositionError) => void;
let successCb: WatchSuccess | null = null;
let errorCb: WatchFailure | null = null;
let watchPosition: ReturnType<typeof vi.fn>;
let clearWatch: ReturnType<typeof vi.fn>;
function fix(over: Partial<GeolocationCoordinates> = {}, timestamp = 1_700_000_000_000): GeolocationPosition {
return {
coords: { latitude: 48.2, longitude: 16.37, accuracy: 12, heading: null, speed: null, altitude: null, altitudeAccuracy: null, ...over },
timestamp,
} as GeolocationPosition;
}
function geoError(code: number, message = 'Location unavailable'): GeolocationPositionError {
return { code, message, PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3 } as GeolocationPositionError;
}
/** Dispatches an orientation event the hook's listener will pick up. */
function orient(props: Record<string, unknown>): void {
const ev = new Event('deviceorientationabsolute');
Object.assign(ev, props);
window.dispatchEvent(ev);
}
beforeEach(() => {
successCb = null;
errorCb = null;
watchPosition = vi.fn((ok: WatchSuccess, fail: WatchFailure) => {
successCb = ok;
errorCb = fail;
return 7;
});
clearWatch = vi.fn();
Object.defineProperty(navigator, 'geolocation', {
value: { watchPosition, clearWatch },
configurable: true,
});
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('useGeolocation', () => {
it('FE-HOOK-GEO-001: starts off with nothing tracked', () => {
const { result } = renderHook(() => useGeolocation());
expect(result.current.mode).toBe('off');
expect(result.current.position).toBeNull();
expect(result.current.error).toBeNull();
expect(watchPosition).not.toHaveBeenCalled();
});
it('FE-HOOK-GEO-002: cycles off → show → follow → off', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
expect(result.current.mode).toBe('show');
expect(watchPosition).toHaveBeenCalledTimes(1);
await act(() => result.current.cycleMode());
expect(result.current.mode).toBe('follow');
await act(() => result.current.cycleMode());
expect(result.current.mode).toBe('off');
expect(clearWatch).toHaveBeenCalledWith(7);
});
it('FE-HOOK-GEO-003: requests a high-accuracy watch', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
expect(watchPosition.mock.calls[0][2]).toEqual({
enableHighAccuracy: true,
maximumAge: 2000,
timeout: 15000,
});
});
it('FE-HOOK-GEO-004: maps a fix onto the position shape', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
act(() => successCb!(fix({ heading: 90, speed: 3.5 })));
expect(result.current.position).toEqual({
lat: 48.2, lng: 16.37, accuracy: 12, heading: 90, speed: 3.5, timestamp: 1_700_000_000_000,
});
});
it('FE-HOOK-GEO-005: reports an error but stays subscribed when the fix merely fails', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
act(() => errorCb!(geoError(2, 'Position unavailable')));
expect(result.current.error).toBe('Position unavailable');
expect(result.current.mode).toBe('show');
expect(clearWatch).not.toHaveBeenCalled();
});
it('FE-HOOK-GEO-006: falls back to a generic message when the error carries none', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
act(() => errorCb!(geoError(3, '')));
expect(result.current.error).toBe('Location unavailable');
});
it('FE-HOOK-GEO-007: a permission denial stops tracking entirely', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
act(() => errorCb!(geoError(1, 'User denied Geolocation')));
expect(result.current.mode).toBe('off');
expect(clearWatch).toHaveBeenCalledWith(7);
});
it('FE-HOOK-GEO-008: refuses to start when the browser has no geolocation', async () => {
// The hook guards with `'geolocation' in navigator`, so the key has to go
// away entirely — a defined-but-undefined property would slip past it.
delete (navigator as { geolocation?: Geolocation }).geolocation;
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
expect(result.current.mode).toBe('off');
expect(result.current.error).toBe('Geolocation is not supported in this browser');
});
it('FE-HOOK-GEO-009: prefers the webkit compass heading', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
act(() => successCb!(fix()));
act(() => orient({ webkitCompassHeading: 120, alpha: 10, absolute: true }));
expect(result.current.position?.heading).toBe(120);
});
it('FE-HOOK-GEO-010: converts a counter-clockwise alpha into a clockwise heading', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
act(() => successCb!(fix()));
act(() => orient({ alpha: 90, absolute: true }));
expect(result.current.position?.heading).toBe(270);
});
it('FE-HOOK-GEO-011: smooths successive headings instead of snapping', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
act(() => successCb!(fix()));
act(() => orient({ alpha: 0, absolute: true }));
expect(result.current.position?.heading).toBe(0);
// 0 → 40 with alpha 0.25 lands a quarter of the way, not at 40.
act(() => orient({ alpha: 320, absolute: true }));
expect(result.current.position?.heading).toBeCloseTo(10, 5);
});
it('FE-HOOK-GEO-012: takes the short way around the 360° seam', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
act(() => successCb!(fix()));
act(() => orient({ alpha: 10, absolute: true })); // heading 350
act(() => orient({ alpha: 350, absolute: true })); // heading 10 — +20 across the seam
expect(result.current.position?.heading).toBeCloseTo(355, 5);
});
it('FE-HOOK-GEO-013a: still uses a non-absolute alpha as a fallback heading', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
act(() => successCb!(fix()));
act(() => orient({ alpha: 90 }));
expect(result.current.position?.heading).toBe(270);
});
it('FE-HOOK-GEO-013: ignores orientation events without a usable angle', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
act(() => successCb!(fix({ heading: 45 })));
act(() => orient({ alpha: null, absolute: true }));
expect(result.current.position?.heading).toBe(45);
});
it('FE-HOOK-GEO-014: keeps the compass heading when the GPS fix has none', async () => {
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
act(() => successCb!(fix()));
act(() => orient({ alpha: 180, absolute: true }));
act(() => successCb!(fix({ heading: null }, 1_700_000_001_000)));
expect(result.current.position?.heading).toBe(180);
});
it('FE-HOOK-GEO-015: setMode accepts a value and a derived updater', async () => {
const { result } = renderHook(() => useGeolocation());
act(() => result.current.setMode('show'));
expect(result.current.mode).toBe('show');
expect(watchPosition).toHaveBeenCalledTimes(1);
act(() => result.current.setMode(prev => (prev === 'show' ? 'follow' : prev)));
expect(result.current.mode).toBe('follow');
// Already watching — no second subscription.
expect(watchPosition).toHaveBeenCalledTimes(1);
act(() => result.current.setMode('off'));
expect(result.current.mode).toBe('off');
expect(result.current.position).toBeNull();
expect(clearWatch).toHaveBeenCalledWith(7);
});
it('FE-HOOK-GEO-016: asks iOS for orientation permission and proceeds either way', async () => {
const requestPermission = vi.fn().mockResolvedValue('denied');
vi.stubGlobal('DeviceOrientationEvent', Object.assign(function () {}, { requestPermission }));
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
expect(requestPermission).toHaveBeenCalled();
expect(result.current.mode).toBe('show');
});
it('FE-HOOK-GEO-017: survives an older webkit that throws from requestPermission', async () => {
const requestPermission = vi.fn().mockRejectedValue(new Error('not allowed'));
vi.stubGlobal('DeviceOrientationEvent', Object.assign(function () {}, { requestPermission }));
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
expect(result.current.mode).toBe('show');
expect(watchPosition).toHaveBeenCalled();
});
it('FE-HOOK-GEO-018: tolerates clearWatch throwing while tearing down', async () => {
clearWatch.mockImplementation(() => { throw new Error('gone'); });
const { result } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
expect(() => act(() => result.current.setMode('off'))).not.toThrow();
});
it('FE-HOOK-GEO-019: stops the watch when the component unmounts', async () => {
const { result, unmount } = renderHook(() => useGeolocation());
await act(() => result.current.cycleMode());
unmount();
expect(clearWatch).toHaveBeenCalledWith(7);
});
});
+249 -1
View File
@@ -4,6 +4,7 @@ import { buildAdmin } from '../../tests/helpers/factories';
import { server } from '../../tests/helpers/msw/server';
import { fireEvent, render, screen, waitFor, within } from '../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../tests/helpers/store';
import { ToastContainer } from '../components/shared/Toast';
import { useAuthStore } from '../store/authStore';
import AdminPage from './AdminPage';
@@ -20,8 +21,24 @@ vi.mock('../components/Admin/GitHubPanel', () => ({
default: () => <div data-testid="github-panel" />,
}));
// AddonManager is stubbed but keeps its two callbacks reachable — the page owns
// the optimistic toggle logic behind them.
vi.mock('../components/Admin/AddonManager', () => ({
default: () => <div data-testid="addon-manager" />,
default: ({
bagTrackingEnabled,
onToggleBagTracking,
onToggleCollabFeature,
}: {
bagTrackingEnabled: boolean;
onToggleBagTracking: () => void;
onToggleCollabFeature: (key: string) => void;
}) => (
<div data-testid="addon-manager">
<span data-testid="bag-tracking-state">{String(bagTrackingEnabled)}</span>
<button onClick={() => onToggleBagTracking()}>toggle bag tracking</button>
<button onClick={() => onToggleCollabFeature('chat')}>toggle chat</button>
</div>
),
}));
vi.mock('../components/Admin/PackingTemplateManager', () => ({
@@ -44,8 +61,27 @@ vi.mock('../components/Admin/DevNotificationsPanel', () => ({
default: () => <div data-testid="dev-notifications-panel" />,
}));
vi.mock('../components/Admin/AdminPluginsPanel', () => ({
default: () => <div data-testid="plugins-panel" />,
}));
vi.mock('../components/Admin/DefaultUserSettingsTab', () => ({
default: () => <div data-testid="default-user-settings" />,
}));
vi.mock('../mobile/screens/admin/MAdmin', () => ({
default: () => <div data-testid="mobile-admin" />,
}));
// Viewport switch — flipped per test instead of at module scope.
let phoneViewport = false;
vi.mock('../mobile/useIsPhone', () => ({
useIsPhone: () => phoneViewport,
}));
beforeEach(() => {
resetAllStores();
phoneViewport = false;
});
describe('AdminPage', () => {
@@ -1406,4 +1442,216 @@ describe('AdminPage', () => {
expect((clientIdInput as HTMLInputElement).value).toBe('my-client-id');
});
});
describe('FE-PAGE-ADMIN-054: Demo baseline button', () => {
it('is hidden unless the instance runs in demo mode', async () => {
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
render(<AdminPage />);
await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument());
expect(screen.queryByRole('button', { name: /save baseline/i })).not.toBeInTheDocument();
});
it('saves the baseline and reports success in demo mode', async () => {
let saved = false;
server.use(
http.post('/api/admin/save-demo-baseline', () => {
saved = true;
return HttpResponse.json({ success: true });
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin(), demoMode: true });
render(
<>
<ToastContainer />
<AdminPage />
</>
);
fireEvent.click(await screen.findByRole('button', { name: /save baseline/i }));
await waitFor(() => expect(saved).toBe(true));
expect(await screen.findByText(/baseline saved/i)).toBeInTheDocument();
});
it('surfaces the server error when the baseline cannot be saved', async () => {
server.use(
http.post('/api/admin/save-demo-baseline', () =>
HttpResponse.json({ error: 'Baseline locked' }, { status: 500 })
)
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin(), demoMode: true });
render(
<>
<ToastContainer />
<AdminPage />
</>
);
fireEvent.click(await screen.findByRole('button', { name: /save baseline/i }));
expect(await screen.findByText('Baseline locked')).toBeInTheDocument();
});
});
describe('FE-PAGE-ADMIN-055: Addons tab toggles', () => {
it('bag tracking flips optimistically and PUTs the new value', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.get('/api/admin/bag-tracking', () => HttpResponse.json({ enabled: false })),
http.put('/api/admin/bag-tracking', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ enabled: true });
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
render(<AdminPage />);
await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /^addons$/i }));
fireEvent.click(screen.getByRole('button', { name: /toggle bag tracking/i }));
expect(screen.getByTestId('bag-tracking-state')).toHaveTextContent('true');
await waitFor(() => expect(body).toEqual({ enabled: true }));
});
it('bag tracking rolls back when the request fails', async () => {
server.use(
http.get('/api/admin/bag-tracking', () => HttpResponse.json({ enabled: false })),
http.put('/api/admin/bag-tracking', () => HttpResponse.json({}, { status: 500 }))
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
render(<AdminPage />);
await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /^addons$/i }));
fireEvent.click(screen.getByRole('button', { name: /toggle bag tracking/i }));
await waitFor(() => expect(screen.getByTestId('bag-tracking-state')).toHaveTextContent('false'));
});
it('a collab feature toggle PUTs only the changed key', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.get('/api/admin/collab-features', () =>
HttpResponse.json({ chat: true, notes: true, polls: true, whatsnext: true })
),
http.put('/api/admin/collab-features', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ success: true });
})
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
render(<AdminPage />);
await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /^addons$/i }));
fireEvent.click(screen.getByRole('button', { name: /toggle chat/i }));
await waitFor(() => expect(body).toEqual({ chat: false }));
});
it('a failing collab toggle restores the previous feature set', async () => {
server.use(
http.get('/api/admin/collab-features', () =>
HttpResponse.json({ chat: true, notes: true, polls: true, whatsnext: true })
),
http.put('/api/admin/collab-features', () => HttpResponse.json({}, { status: 500 }))
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
render(<AdminPage />);
await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /^addons$/i }));
fireEvent.click(screen.getByRole('button', { name: /toggle chat/i }));
// The rollback re-renders the stub; the addon panel stays mounted either way
await waitFor(() => expect(screen.getByTestId('addon-manager')).toBeInTheDocument());
});
});
describe('FE-PAGE-ADMIN-056: Dev notifications tab', () => {
it('is hidden unless devMode is on and renders the panel when it is', async () => {
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
const { unmount } = render(<AdminPage />);
await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument());
expect(screen.queryByRole('button', { name: /dev: notifications/i })).not.toBeInTheDocument();
unmount();
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin(), devMode: true });
render(<AdminPage />);
const devTab = await screen.findByRole('button', { name: /dev: notifications/i });
fireEvent.click(devTab);
expect(screen.getByTestId('dev-notifications-panel')).toBeInTheDocument();
});
});
describe('FE-PAGE-ADMIN-057: Remaining tab panels', () => {
it('renders the personalization, plugins and user-defaults panels', async () => {
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
render(<AdminPage />);
await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /^personalization$/i }));
expect(screen.getByTestId('packing-template-manager')).toBeInTheDocument();
expect(screen.getByTestId('category-manager')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /^plugins$/i }));
expect(screen.getByTestId('plugins-panel')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /user defaults/i }));
expect(screen.getByTestId('default-user-settings')).toBeInTheDocument();
});
});
describe('FE-PAGE-ADMIN-058: Phone viewport', () => {
it('renders the mobile admin screen instead of the desktop layout', async () => {
phoneViewport = true;
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
render(<AdminPage />);
expect(screen.getByTestId('mobile-admin')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /^users$/i })).not.toBeInTheDocument();
});
});
describe('FE-PAGE-ADMIN-059: Stats fallbacks', () => {
it('shows a zero file count when the API omits totalFiles', async () => {
server.use(
http.get('/api/admin/stats', () =>
HttpResponse.json({ totalUsers: 3, totalTrips: 11, totalPlaces: 42 })
)
);
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
render(<AdminPage />);
const filesLabel = await screen.findByText('Files');
expect(within(filesLabel.closest<HTMLElement>('div.rounded-xl')!).getByText('0')).toBeInTheDocument();
});
it('hides the stats grid entirely when stats cannot be loaded', async () => {
server.use(http.get('/api/admin/stats', () => HttpResponse.json({}, { status: 500 })));
seedStore(useAuthStore, { isAuthenticated: true, user: buildAdmin() });
render(<AdminPage />);
await waitFor(() => expect(screen.getByRole('button', { name: /^users$/i })).toBeInTheDocument());
expect(screen.queryByText('Files')).not.toBeInTheDocument();
});
});
});
+665
View File
@@ -0,0 +1,665 @@
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { http, HttpResponse } from 'msw';
import { render, screen, fireEvent, waitFor } from '../../tests/helpers/render';
import { server } from '../../tests/helpers/msw/server';
import { buildAtlasController, buildAtlasData, buildBucketItem, buildCountryDetail, type VisitedRegions } from '../../tests/helpers/atlas';
import type { AtlasController } from '../mobile/screens/atlas/atlasController';
import type { AtlasData, CountryDetail } from './atlas/atlasModel';
import AtlasPage from './AtlasPage';
// FE-PAGE-ATLASW-001 to FE-PAGE-ATLASW-026
//
// AtlasPage is a wiring container around useAtlas: the hook is mocked here so the
// confirm popup and the sidebar can be driven into every state directly, which the
// map-click driven suite in AtlasPage.test.tsx cannot reach.
const mocks = vi.hoisted(() => ({ atlas: {} as AtlasController, isPhone: false }));
vi.mock('./atlas/useAtlas', () => ({ useAtlas: () => mocks.atlas }));
vi.mock('../mobile/useIsPhone', () => ({ useIsPhone: () => mocks.isPhone }));
vi.mock('../components/Layout/Navbar', () => ({
default: () => React.createElement('nav', { 'data-testid': 'navbar' }),
}));
const toast = vi.fn(() => 0);
function setAtlas(over: Record<string, unknown> = {}): AtlasController {
mocks.atlas = buildAtlasController(over);
return mocks.atlas;
}
/** The two CustomSelect triggers in a popup both render the "—" placeholder option. */
function selectTriggers(): HTMLElement[] {
return screen.getAllByRole('button').filter((b) => b.textContent?.trim() === '—');
}
beforeEach(() => {
mocks.isPhone = false;
toast.mockClear();
window.__addToast = toast;
setAtlas();
server.use(
http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ success: true })),
http.post('/api/addons/atlas/region/:code/mark', () => HttpResponse.json({ success: true })),
http.delete('/api/addons/atlas/region/:code/mark', () => HttpResponse.json({ success: true })),
http.post('/api/addons/atlas/bucket-list', () =>
HttpResponse.json({ item: buildBucketItem({ id: 99, name: 'Germany', country_code: 'DE' }) }),
),
);
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('AtlasPage wiring', () => {
it('FE-PAGE-ATLASW-001: hands the whole screen to the mobile atlas on a phone', () => {
mocks.isPhone = true;
render(<AtlasPage />);
expect(screen.getByRole('button', { name: 'atlas.bucketTab' })).toBeInTheDocument();
expect(screen.queryByTestId('navbar')).not.toBeInTheDocument();
});
it('FE-PAGE-ATLASW-002: shows navbar and spinner while the atlas is loading', () => {
setAtlas({ loading: true });
render(<AtlasPage />);
expect(screen.getByTestId('navbar')).toBeInTheDocument();
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
});
describe('country popup', () => {
it('FE-PAGE-ATLASW-003: the choose popup marks a country and updates the local atlas data', async () => {
const atlas = setAtlas({ confirmAction: { type: 'choose', code: 'DE', name: 'Germany' } });
render(<AtlasPage />);
const flag = document.querySelector('img[alt="DE"]') as HTMLImageElement;
expect(flag.src).toContain('flagcdn.com/w80/de.png');
const markBtn = screen.getByText('atlas.markVisited').closest('button') as HTMLButtonElement;
fireEvent.mouseEnter(markBtn);
expect(markBtn.style.background).toBe('var(--bg-secondary)');
fireEvent.mouseLeave(markBtn);
expect(markBtn.style.background).toBe('none');
fireEvent.click(markBtn);
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
const data = atlas.data as AtlasData;
expect(data.countries.map((c) => c.code)).toEqual(['FR', 'DE']);
expect(data.stats.totalCountries).toBe(2);
expect(data.continents?.Europe).toBe(2);
});
it('FE-PAGE-ATLASW-004: a failing mark shows the server error as a toast', async () => {
setAtlas({ confirmAction: { type: 'choose', code: 'DE', name: 'Germany' } });
server.use(
http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ error: 'Locked' }, { status: 400 })),
);
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.markVisited'));
await waitFor(() => expect(toast).toHaveBeenCalledWith('Locked', 'error', undefined));
});
it('FE-PAGE-ATLASW-005: the bucket option and the backdrop drive the pending action', () => {
const action = { type: 'choose', code: 'DE', name: 'Germany' } as AtlasController['confirmAction'];
const atlas = setAtlas({ confirmAction: action });
render(<AtlasPage />);
const bucketBtn = screen.getByText('atlas.addToBucket').closest('button') as HTMLButtonElement;
fireEvent.mouseEnter(bucketBtn);
fireEvent.mouseLeave(bucketBtn);
fireEvent.click(bucketBtn);
expect(atlas.setConfirmAction).toHaveBeenCalledWith({ ...action, type: 'bucket' });
fireEvent.click(screen.getByText('Germany').closest('div[style*="z-index: 1000"]') as HTMLElement);
expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null);
});
it('FE-PAGE-ATLASW-006: a three-letter code falls back to the flag glyph', () => {
setAtlas({ confirmAction: { type: 'choose', code: 'DEU', name: 'Germany' } });
render(<AtlasPage />);
expect(document.querySelector('img[alt="DEU"]')).toBeNull();
expect(screen.getByText('Germany')).toBeInTheDocument();
});
it('FE-PAGE-ATLASW-007: the region popup marks a region and adopts its country', async () => {
const atlas = setAtlas({
confirmAction: { type: 'choose-region', code: 'ES', name: 'Galicia', regionCode: 'ES-GA', countryName: 'Spain' },
});
render(<AtlasPage />);
expect(screen.getByText('Spain')).toBeInTheDocument();
const markBtn = screen.getByText('atlas.markVisited').closest('button') as HTMLButtonElement;
fireEvent.mouseEnter(markBtn);
fireEvent.mouseLeave(markBtn);
fireEvent.click(markBtn);
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
expect((atlas.visitedRegions as VisitedRegions).ES).toEqual([
{ code: 'ES-GA', name: 'Galicia', placeCount: 0, manuallyMarked: true },
]);
expect((atlas.data as AtlasData).countries.map((c) => c.code)).toContain('ES');
});
it('FE-PAGE-ATLASW-008: an already recorded region is not added twice and the country stays put', async () => {
const regions: VisitedRegions = { FR: [{ code: 'FR-BRE', name: 'Bretagne', placeCount: 2 }] };
const atlas = setAtlas({
confirmAction: { type: 'choose-region', code: 'FR', name: 'Bretagne', regionCode: 'FR-BRE', countryName: 'France' },
visitedRegions: regions,
});
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.markVisited'));
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
expect(atlas.visitedRegions).toBe(regions);
expect((atlas.data as AtlasData).countries).toHaveLength(1);
});
it('FE-PAGE-ATLASW-009: a failing region mark shows the error toast', async () => {
setAtlas({ confirmAction: { type: 'choose-region', code: 'ES', name: 'Galicia', regionCode: 'ES-GA' } });
server.use(
http.post('/api/addons/atlas/region/:code/mark', () => HttpResponse.json({ error: 'Nope' }, { status: 422 })),
);
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.markVisited'));
await waitFor(() => expect(toast).toHaveBeenCalledWith('Nope', 'error', undefined));
});
it('FE-PAGE-ATLASW-010: a region popup without a region code cannot be confirmed', async () => {
const atlas = setAtlas({ confirmAction: { type: 'choose-region', code: 'ES', name: 'Galicia' } });
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.markVisited'));
fireEvent.click(screen.getByText('atlas.addToBucket'));
expect(atlas.setVisitedRegions).not.toHaveBeenCalled();
expect(atlas.setConfirmAction).toHaveBeenCalledWith({ type: 'bucket', code: 'ES', name: 'Galicia' });
});
it('FE-PAGE-ATLASW-010b: the region bucket option highlights on hover', () => {
const action = { type: 'choose-region', code: 'ES', name: 'Galicia', regionCode: 'ES-GA' } as AtlasController['confirmAction'];
const atlas = setAtlas({ confirmAction: action });
render(<AtlasPage />);
const bucketBtn = screen.getByText('atlas.addToBucket').closest('button') as HTMLButtonElement;
fireEvent.mouseEnter(bucketBtn);
expect(bucketBtn.style.background).toBe('var(--bg-secondary)');
fireEvent.mouseLeave(bucketBtn);
expect(bucketBtn.style.background).toBe('none');
fireEvent.click(bucketBtn);
expect(atlas.setConfirmAction).toHaveBeenCalledWith({ ...action, type: 'bucket' });
});
it('FE-PAGE-ATLASW-010c: a region removal without a region code performs no request', async () => {
const deleteSpy = vi.fn();
server.use(
http.delete('/api/addons/atlas/region/:code/mark', () => { deleteSpy(); return HttpResponse.json({}); }),
);
const atlas = setAtlas({ confirmAction: { type: 'unmark-region', code: 'ES', name: 'Galicia' } });
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.unmark'));
await waitFor(() => expect(atlas.setVisitedRegions).not.toHaveBeenCalled());
expect(deleteSpy).not.toHaveBeenCalled();
});
it('FE-PAGE-ATLASW-010d: marking a country that is already known leaves the totals alone', async () => {
const atlas = setAtlas({ confirmAction: { type: 'choose', code: 'FR', name: 'France' } });
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.markVisited'));
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
expect((atlas.data as AtlasData).stats.totalCountries).toBe(1);
});
it('FE-PAGE-ATLASW-010e: region actions cope with atlas data that never loaded', async () => {
const atlas = setAtlas({
confirmAction: { type: 'unmark-region', code: 'ES', name: 'Galicia', regionCode: 'ES-GA' },
data: null,
});
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.unmark'));
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
expect(atlas.data).toBeNull();
});
it('FE-PAGE-ATLASW-011: the unmark popup cancels or delegates to the shared executor', () => {
const atlas = setAtlas({ confirmAction: { type: 'unmark', code: 'FR', name: 'France' } });
render(<AtlasPage />);
expect(screen.getByText('atlas.confirmUnmark')).toBeInTheDocument();
fireEvent.click(screen.getByText('common.cancel'));
expect(atlas.setConfirmAction).toHaveBeenCalledWith(null);
fireEvent.click(screen.getByText('atlas.unmark'));
expect(atlas.executeConfirmAction).toHaveBeenCalled();
});
it('FE-PAGE-ATLASW-012: the mark confirmation cancels or delegates to the shared executor', () => {
const atlas = setAtlas({ confirmAction: { type: 'mark', code: 'DE', name: 'Germany' } });
render(<AtlasPage />);
expect(screen.getByText('atlas.confirmMark')).toBeInTheDocument();
fireEvent.click(screen.getByText('common.cancel'));
expect(atlas.setConfirmAction).toHaveBeenCalledWith(null);
fireEvent.click(screen.getByText('atlas.markVisited'));
expect(atlas.executeConfirmAction).toHaveBeenCalled();
});
it('FE-PAGE-ATLASW-013: removing the last region of a data-free country drops the country as well', async () => {
const atlas = setAtlas({
confirmAction: { type: 'unmark-region', code: 'IT', name: 'Lazio', regionCode: 'IT-62', countryName: 'Italy' },
visitedRegions: { IT: [{ code: 'IT-62', name: 'Lazio', placeCount: 0 }] } as VisitedRegions,
data: buildAtlasData({
countries: [
{ code: 'FR', tripCount: 2, placeCount: 5 },
{ code: 'IT', tripCount: 0, placeCount: 0 },
],
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 2, totalDays: 14 },
continents: { Europe: 2 },
}),
});
render(<AtlasPage />);
expect(screen.getByText('Italy')).toBeInTheDocument();
expect(screen.getByText('atlas.confirmUnmarkRegion')).toBeInTheDocument();
fireEvent.click(screen.getByText('common.cancel'));
expect(atlas.setConfirmAction).toHaveBeenCalledWith(null);
fireEvent.click(screen.getByText('atlas.unmark'));
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null));
expect(atlas.visitedRegions).toEqual({});
const data = atlas.data as AtlasData;
expect(data.countries.map((c) => c.code)).toEqual(['FR']);
expect(data.stats.totalCountries).toBe(1);
expect(data.continents?.Europe).toBe(1);
});
it('FE-PAGE-ATLASW-014: a country with other regions left keeps its entry', async () => {
const atlas = setAtlas({
confirmAction: { type: 'unmark-region', code: 'IT', name: 'Lazio', regionCode: 'IT-62' },
visitedRegions: {
IT: [
{ code: 'IT-62', name: 'Lazio', placeCount: 0 },
{ code: 'IT-25', name: 'Lombardia', placeCount: 0 },
],
} as VisitedRegions,
data: buildAtlasData({
countries: [{ code: 'IT', tripCount: 0, placeCount: 0 }],
stats: { totalTrips: 0, totalPlaces: 0, totalCountries: 1, totalDays: 0 },
}),
});
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.unmark'));
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
expect((atlas.visitedRegions as VisitedRegions).IT.map((r) => r.code)).toEqual(['IT-25']);
expect((atlas.data as AtlasData).countries).toHaveLength(1);
});
it('FE-PAGE-ATLASW-015: a failing region removal shows the error toast', async () => {
setAtlas({ confirmAction: { type: 'unmark-region', code: 'IT', name: 'Lazio', regionCode: 'IT-62' } });
server.use(
http.delete('/api/addons/atlas/region/:code/mark', () => HttpResponse.json({ error: 'Boom' }, { status: 500 })),
);
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.unmark'));
await waitFor(() => expect(toast).toHaveBeenCalledWith('Boom', 'error', undefined));
});
it('FE-PAGE-ATLASW-016: the bucket step offers a month and a year picker', () => {
const atlas = setAtlas({ confirmAction: { type: 'bucket', code: 'DE', name: 'Germany' } });
render(<AtlasPage />);
expect(screen.getByText('atlas.bucketWhen')).toBeInTheDocument();
const [monthTrigger, yearTrigger] = selectTriggers();
fireEvent.click(monthTrigger);
fireEvent.click(screen.getByText('March'));
expect(atlas.setBucketMonth).toHaveBeenCalledWith(3);
const nextYear = String(new Date().getFullYear() + 1);
fireEvent.click(yearTrigger);
fireEvent.click(screen.getByText(nextYear));
expect(atlas.setBucketYear).toHaveBeenCalledWith(Number(nextYear));
});
it('FE-PAGE-ATLASW-016b: a chosen month and year is posted as the target date and reset afterwards', async () => {
let body: unknown = null;
server.use(
http.post('/api/addons/atlas/bucket-list', async ({ request }) => {
body = await request.json();
return HttpResponse.json({ item: buildBucketItem({ id: 99, name: 'Germany', country_code: 'DE', target_date: '2027-05' }) });
}),
);
const atlas = setAtlas({
confirmAction: { type: 'bucket', code: 'DE', name: 'Germany' },
bucketMonth: 5,
bucketYear: 2027,
});
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.addToBucket'));
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenLastCalledWith(null));
expect(body).toEqual({ name: 'Germany', country_code: 'DE', target_date: '2027-05' });
expect(atlas.bucketList as unknown[]).toHaveLength(1);
expect(atlas.setBucketMonth).toHaveBeenLastCalledWith(0);
expect(atlas.setBucketYear).toHaveBeenLastCalledWith(0);
});
it('FE-PAGE-ATLASW-017: without a month and year the bucket item is posted open-ended', async () => {
let body: unknown = null;
server.use(
http.post('/api/addons/atlas/bucket-list', async ({ request }) => {
body = await request.json();
return HttpResponse.json({ item: buildBucketItem({ id: 100, name: 'Bretagne' }) });
}),
);
const atlas = setAtlas({ confirmAction: { type: 'bucket', code: 'FR', name: 'Bretagne', regionCode: 'FR-BRE' } });
render(<AtlasPage />);
fireEvent.click(screen.getByText('common.back'));
expect(atlas.setConfirmAction).toHaveBeenCalledWith({
type: 'choose-region', code: 'FR', name: 'Bretagne', regionCode: 'FR-BRE',
});
fireEvent.click(screen.getByText('atlas.addToBucket'));
await waitFor(() => expect(body).toEqual({ name: 'Bretagne', country_code: 'FR', target_date: null }));
});
it('FE-PAGE-ATLASW-018: a failing bucket post shows the error toast', async () => {
server.use(
http.post('/api/addons/atlas/bucket-list', () => HttpResponse.json({ error: 'Full' }, { status: 400 })),
);
setAtlas({ confirmAction: { type: 'bucket', code: 'DE', name: 'Germany' } });
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.addToBucket'));
await waitFor(() => expect(toast).toHaveBeenCalledWith('Full', 'error', undefined));
});
});
describe('sidebar', () => {
it('FE-PAGE-ATLASW-019: the stats tab lists totals, continents ordered by size and the last trip', () => {
const atlas = setAtlas({
data: buildAtlasData({
continents: { Europe: 3, Asia: 5, Africa: 1 },
stats: { totalTrips: 6, totalPlaces: 40, totalCountries: 9, totalDays: 55, totalCities: 12 },
streak: 1,
tripsThisYear: 1,
}),
});
render(<AtlasPage />);
// Every total shows twice: once in the mobile bar, once in the desktop panel.
expect(screen.getAllByText('9')).toHaveLength(2);
expect(screen.getAllByText('40')).toHaveLength(2);
expect(screen.getByText('atlas.europe')).toBeInTheDocument();
// Singular labels are picked when streak / tripsThisYear are 1.
expect(screen.getByText('atlas.yearInRow')).toBeInTheDocument();
expect(screen.getByText(/atlas\.tripIn/)).toBeInTheDocument();
fireEvent.click(screen.getByText('Paris Trip'));
expect(atlas.navigate).toHaveBeenCalledWith('/trips/7');
});
it('FE-PAGE-ATLASW-020: an empty atlas shows the mascot empty state instead of the stats', () => {
setAtlas({ data: buildAtlasData({ countries: [], lastTrip: null, continents: {} }) });
render(<AtlasPage />);
expect(screen.getByText('atlas.noData')).toBeInTheDocument();
expect(screen.queryByText('atlas.lastTrip')).not.toBeInTheDocument();
});
it('FE-PAGE-ATLASW-021: the country detail overlay lists trips and offers the manual unmark', () => {
const atlas = setAtlas({
selectedCountry: 'FR',
countryDetail: buildCountryDetail({
places: [{ id: 1 }, { id: 2 }, { id: 3 }] as unknown as CountryDetail['places'],
trips: [
{ id: 11, title: 'Paris' },
{ id: 12, title: 'Nice' },
{ id: 13, title: 'Lyon' },
{ id: 14, title: 'Brest' },
],
manually_marked: true,
}),
});
render(<AtlasPage />);
expect(screen.getByText('France')).toBeInTheDocument();
expect(screen.getByText('3 atlas.places · 4 Trips')).toBeInTheDocument();
// Only the first three trips are shown.
expect(screen.queryByText('Brest')).not.toBeInTheDocument();
fireEvent.click(screen.getByText('Nice'));
expect(atlas.navigate).toHaveBeenCalledWith('/trips/12');
fireEvent.click(screen.getByText('atlas.unmark'));
expect(atlas.handleUnmarkCountry).toHaveBeenCalledWith('FR');
});
it('FE-PAGE-ATLASW-022: the stats panel measures itself through a ResizeObserver', () => {
const observeSpy = vi.fn();
const disconnectSpy = vi.fn();
vi.stubGlobal(
'ResizeObserver',
class {
observe = observeSpy;
unobserve = vi.fn();
disconnect = disconnectSpy;
constructor(cb: ResizeObserverCallback) {
cb([], this as unknown as ResizeObserver);
}
},
);
const { unmount } = render(<AtlasPage />);
expect(observeSpy).toHaveBeenCalled();
unmount();
expect(disconnectSpy).toHaveBeenCalled();
});
it('FE-PAGE-ATLASW-023: the bucket tab renders items with target month, notes and a delete action', () => {
const atlas = setAtlas({
bucketTab: 'bucket',
bucketList: [
buildBucketItem({ id: 1, name: 'Kyoto', country_code: 'JPN', target_date: '2027-04' }),
buildBucketItem({ id: 2, name: 'Patagonia', country_code: null, notes: 'road trip' }),
buildBucketItem({ id: 3, name: 'Lisbon', country_code: 'PT', target_date: '2030' }),
],
});
render(<AtlasPage />);
expect(screen.getByText('Kyoto')).toBeInTheDocument();
expect(screen.getByText('Apr 2027')).toBeInTheDocument();
expect(screen.getByText('road trip')).toBeInTheDocument();
expect(screen.getByText('2030')).toBeInTheDocument();
expect((document.querySelector('img[alt="JP"]') as HTMLImageElement).src).toContain('flagcdn.com/w40/jp.png');
const deleteBtn = screen.getByText('Patagonia').closest('div')?.querySelector('button') as HTMLButtonElement;
fireEvent.click(deleteBtn);
expect(atlas.handleDeleteBucketItem).toHaveBeenCalledWith(2);
fireEvent.click(screen.getByText('atlas.addPoi'));
expect(atlas.setShowBucketAdd).toHaveBeenCalledWith(true);
});
it('FE-PAGE-ATLASW-024: the bucket add form searches, picks a result and submits', () => {
const atlas = setAtlas({
bucketTab: 'bucket',
showBucketAdd: true,
bucketSearch: 'kyo',
bucketSearchResults: [{ name: 'Kyoto', address: 'Japan' }],
});
render(<AtlasPage />);
const nameInput = screen.getByPlaceholderText('atlas.bucketNamePlaceholder');
expect(nameInput).toHaveValue('kyo');
fireEvent.change(nameInput, { target: { value: 'kyot' } });
expect(atlas.setBucketSearch).toHaveBeenCalledWith('kyot');
fireEvent.keyDown(nameInput, { key: 'Enter' });
expect(atlas.handleBucketPoiSearch).toHaveBeenCalled();
fireEvent.click(screen.getByText('Kyoto'));
expect(atlas.handleSelectBucketPoi).toHaveBeenCalledWith({ name: 'Kyoto', address: 'Japan' });
const [monthTrigger, yearTrigger] = selectTriggers();
fireEvent.click(monthTrigger);
fireEvent.click(screen.getByText('Mar'));
expect(atlas.setBucketPoiMonth).toHaveBeenCalledWith(3);
const nextYear = String(new Date().getFullYear() + 2);
fireEvent.click(yearTrigger);
fireEvent.click(screen.getByText(nextYear));
expect(atlas.setBucketPoiYear).toHaveBeenCalledWith(Number(nextYear));
fireEvent.click(screen.getByText('common.cancel'));
expect(atlas.setShowBucketAdd).toHaveBeenCalledWith(false);
expect(atlas.setBucketForm).toHaveBeenCalledWith({ name: '', notes: '', lat: '', lng: '', target_date: '' });
});
it('FE-PAGE-ATLASW-025: a picked place shows its coordinates and can be cleared again', () => {
const atlas = setAtlas({
bucketTab: 'bucket',
showBucketAdd: true,
bucketForm: { name: 'Kyoto', notes: '', lat: '35.0116', lng: '135.7681', target_date: '' },
});
render(<AtlasPage />);
expect(screen.getByText(/35\.0116, 135\.7681/)).toBeInTheDocument();
const nameInput = screen.getByPlaceholderText('atlas.bucketNamePlaceholder');
fireEvent.change(nameInput, { target: { value: 'Kyoto old town' } });
expect(atlas.setBucketForm).toHaveBeenCalledWith({
name: 'Kyoto old town', notes: '', lat: '35.0116', lng: '135.7681', target_date: '',
});
fireEvent.keyDown(nameInput, { key: 'Enter' });
expect(atlas.handleAddBucketItem).toHaveBeenCalled();
fireEvent.keyDown(nameInput, { key: 'Escape' });
expect(atlas.setShowBucketAdd).toHaveBeenCalledWith(false);
const clearBtn = nameInput.parentElement?.querySelector('button') as HTMLButtonElement;
fireEvent.click(clearBtn);
expect(atlas.setBucketForm).toHaveBeenLastCalledWith({
name: '', notes: '', lat: '', lng: '', target_date: '',
});
fireEvent.click(screen.getByText('common.add'));
expect(atlas.handleAddBucketItem).toHaveBeenCalledTimes(2);
});
it('FE-PAGE-ATLASW-026: the tab bar switches between stats and bucket list', () => {
const atlas = setAtlas({ bucketList: [] });
render(<AtlasPage />);
expect(screen.getByText('atlas.bucketEmptyHint')).toBeInTheDocument();
fireEvent.click(screen.getByText('atlas.bucketTab'));
expect(atlas.setBucketTab).toHaveBeenCalledWith('bucket');
fireEvent.click(screen.getByText('atlas.statsTab'));
expect(atlas.setBucketTab).toHaveBeenCalledWith('stats');
});
});
describe('appearance', () => {
afterEach(() => {
document.documentElement.removeAttribute('data-no-transparency');
});
it('FE-PAGE-ATLASW-027: the no-transparency setting paints the tooltip and the panel opaque', () => {
document.documentElement.setAttribute('data-no-transparency', '');
const atlas = setAtlas();
const { unmount } = render(<AtlasPage />);
const tooltip = atlas.regionTooltipRef.current as HTMLElement;
const panel = atlas.panelRef.current as HTMLElement;
expect(tooltip.style.background).toBe('rgb(255, 255, 255)');
expect(panel.style.background).toBe('rgb(255, 255, 255)');
unmount();
const darkAtlas = setAtlas({ dark: true });
render(<AtlasPage />);
expect((darkAtlas.regionTooltipRef.current as HTMLElement).style.background).toBe('rgb(15, 15, 20)');
expect((darkAtlas.panelRef.current as HTMLElement).style.background).toBe('rgb(21, 21, 28)');
});
it('FE-PAGE-ATLASW-028: without the setting both surfaces stay translucent', () => {
const atlas = setAtlas();
render(<AtlasPage />);
expect((atlas.regionTooltipRef.current as HTMLElement).style.background).toBe('rgba(255, 255, 255, 0.96)');
expect((atlas.panelRef.current as HTMLElement).style.background).toBe('rgba(255, 255, 255, 0.2)');
});
});
describe('continent bookkeeping', () => {
it('FE-PAGE-ATLASW-029: marking a region on a new continent starts that continent at one', async () => {
const atlas = setAtlas({
confirmAction: { type: 'choose-region', code: 'JP', name: 'Kansai', regionCode: 'JP-27' },
});
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.markVisited'));
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
const data = atlas.data as AtlasData;
// Europe was the only known continent; Asia is added from zero.
expect(data.continents).toEqual({ Europe: 1, Asia: 1 });
expect(data.stats.totalCountries).toBe(2);
});
it('FE-PAGE-ATLASW-030: removing a country that has no recorded regions clamps its continent at zero', async () => {
const atlas = setAtlas({
confirmAction: { type: 'unmark-region', code: 'JP', name: 'Kansai', regionCode: 'JP-27' },
visitedRegions: {} as VisitedRegions,
data: buildAtlasData({
countries: [{ code: 'JP', tripCount: 0, placeCount: 0, firstVisit: null, lastVisit: null }],
stats: { totalTrips: 0, totalPlaces: 0, totalCountries: 1, totalDays: 0 },
continents: { Europe: 1 },
}),
});
render(<AtlasPage />);
fireEvent.click(screen.getByText('atlas.unmark'));
await waitFor(() => expect(atlas.setConfirmAction).toHaveBeenCalledWith(null));
const data = atlas.data as AtlasData;
expect(data.countries).toHaveLength(0);
expect(data.stats.totalCountries).toBe(0);
// Asia was never counted, so the decrement floors at 0 instead of going negative.
expect(data.continents).toEqual({ Europe: 1, Asia: 0 });
});
it('FE-PAGE-ATLASW-031: backing out of the bucket step returns to the country chooser', () => {
const atlas = setAtlas({ confirmAction: { type: 'bucket', code: 'DE', name: 'Germany' } });
render(<AtlasPage />);
fireEvent.click(screen.getByText('common.back'));
expect(atlas.setConfirmAction).toHaveBeenCalledWith({ type: 'choose', code: 'DE', name: 'Germany' });
});
});
});
@@ -0,0 +1,754 @@
// FE-PAGE-COLLPAGE-001 to FE-PAGE-COLLPAGE-030
// Structural coverage for the desktop Collections page: which branch of the body
// renders, which affordances a role gets, and that every child callback is wired
// to the hook. The page follows the Page pattern, so useCollections is mocked and
// each child is stubbed with a prop-driven button.
import React from 'react'
import { render, screen, fireEvent } from '../../tests/helpers/render'
import CollectionsPage from './CollectionsPage'
vi.mock('../components/Layout/Navbar', () => ({ default: () => <nav data-testid="navbar" /> }))
vi.mock('../mobile/screens/collections/MCollections', () => ({ default: () => <div data-testid="mobile-collections" /> }))
let isPhone = false
vi.mock('../mobile/useIsPhone', () => ({ useIsPhone: () => isPhone }))
vi.mock('../components/Collections/ListsRail', () => ({
default: (p: {
onSelect: (id: number) => void
onNewList: () => void
onAcceptInvite: (id: number) => void
onDeclineInvite: (id: number) => void
}) => (
<div data-testid="rail">
<button type="button" onClick={() => p.onSelect(2)}>rail-select</button>
<button type="button" onClick={p.onNewList}>rail-new</button>
<button type="button" onClick={() => p.onAcceptInvite(3)}>rail-accept</button>
<button type="button" onClick={() => p.onDeclineInvite(3)}>rail-decline</button>
</div>
),
}))
vi.mock('../components/Collections/CollectionHero', () => ({
default: (p: { eyebrow: string; title: string; canEdit: boolean; onEdit: () => void; onShare: () => void }) => (
<div data-testid="hero">
<span data-testid="hero-eyebrow">{p.eyebrow}</span>
<span data-testid="hero-title">{p.title}</span>
{p.canEdit && <button type="button" onClick={p.onEdit}>hero-edit</button>}
<button type="button" onClick={p.onShare}>hero-share</button>
</div>
),
}))
vi.mock('../components/Collections/CollectionList', () => ({
default: (p: { places: { id: number }[]; onOpenPlace: (id: number) => void; onStatusChange?: (id: number, s: string) => void }) => (
<div data-testid="list">
<span data-testid="list-count">{p.places.length}</span>
<span data-testid="list-can-status">{p.onStatusChange ? 'yes' : 'no'}</span>
<button type="button" onClick={() => p.onOpenPlace(10)}>list-open</button>
</div>
),
}))
vi.mock('../components/Collections/CollectionFilterBar', () => ({
default: (p: { canAddPlace?: boolean; onAddPlace: () => void; showLabels: boolean; canManageLabels: boolean; onManageLabels: () => void; showSelect: boolean; onToggleSelect: () => void }) => (
<div data-testid="filterbar">
<span data-testid="filter-flags">{`${p.showLabels}|${p.canManageLabels}|${p.showSelect}`}</span>
{p.canAddPlace && <button type="button" onClick={p.onAddPlace}>filter-add</button>}
<button type="button" onClick={p.onManageLabels}>filter-labels</button>
<button type="button" onClick={p.onToggleSelect}>filter-select</button>
</div>
),
}))
vi.mock('../components/Collections/CollectionMapPanel', () => ({
default: (p: { overlay: boolean; places: { id: number }[]; onSelect: (id: number) => void; onDeselect: () => void; onToggleView: () => void; onSearch: (v: string) => void }) => (
<div data-testid={p.overlay ? 'map-overlay' : 'map-plain'}>
<span data-testid="map-count">{p.places.length}</span>
<button type="button" onClick={() => p.onSelect(10)}>map-select</button>
<button type="button" onClick={p.onDeselect}>map-deselect</button>
<button type="button" onClick={p.onToggleView}>map-toggle</button>
<button type="button" onClick={() => p.onSearch('cafe')}>map-search</button>
</div>
),
}))
vi.mock('../components/Collections/CopyToTripModal', () => ({
default: (p: { isOpen: boolean; placeIds: number[]; onClose: () => void }) =>
p.isOpen ? <div data-testid="copy-modal">{p.placeIds.join(',')}<button type="button" onClick={p.onClose}>copy-close</button></div> : null,
}))
vi.mock('../components/Collections/MoveToListModal', () => ({
default: (p: { mode: string; lists: { id: number }[]; count: number; onPick: (id: number) => void; onClose: () => void }) => (
<div data-testid="move-modal">
<span data-testid="move-mode">{p.mode}</span>
<span data-testid="move-lists">{p.lists.map(l => l.id).join(',')}</span>
<button type="button" onClick={() => p.onPick(9)}>move-pick</button>
<button type="button" onClick={p.onClose}>move-close</button>
</div>
),
}))
vi.mock('../components/Collections/ShareCollectionModal', () => ({
default: (p: { isOpen: boolean; onClose: () => void; onAfterLeave: () => void }) =>
p.isOpen ? <div data-testid="share-modal"><button type="button" onClick={p.onClose}>share-close</button><button type="button" onClick={p.onAfterLeave}>share-leave</button></div> : null,
}))
vi.mock('../components/Collections/AddPlaceToCollectionModal', () => ({
default: (p: { isOpen: boolean; collectionId: number; onClose: () => void; onAdded: () => void }) =>
p.isOpen ? <div data-testid="addplace-modal">{p.collectionId}<button type="button" onClick={p.onClose}>addplace-close</button><button type="button" onClick={p.onAdded}>addplace-added</button></div> : null,
}))
vi.mock('../components/Collections/CollectionPlaceDetail', () => ({
default: (p: {
place: { id: number }
anchorRect: { left: number; width: number } | null
onClose: () => void
onSetStatus: (s: string) => void
onSave: (patch: Record<string, unknown>) => void
onUploadImage: (f: File) => void
onCopyToTrip: () => void
onRemove: () => void
onRate: (r: number) => void
}) => (
<div data-testid="detail">
<span data-testid="detail-anchored">{p.anchorRect ? 'docked' : 'sheet'}</span>
<button type="button" onClick={p.onClose}>detail-close</button>
<button type="button" onClick={() => p.onSetStatus('visited')}>detail-status</button>
<button type="button" onClick={() => p.onSave({ notes: 'hi' })}>detail-save</button>
<button type="button" onClick={() => p.onUploadImage(new File(['x'], 'a.png'))}>detail-upload</button>
<button type="button" onClick={p.onCopyToTrip}>detail-copy</button>
<button type="button" onClick={p.onRemove}>detail-remove</button>
<button type="button" onClick={() => p.onRate(4)}>detail-rate</button>
</div>
),
}))
vi.mock('../components/Collections/ListEditorModal', () => ({
default: (p: { target: unknown; onClose: () => void; onCreated: (id: number) => void; onRequestDelete: (id: number) => void }) => (
<div data-testid="editor">
<span data-testid="editor-target">{p.target === null ? 'closed' : String(p.target)}</span>
<button type="button" onClick={p.onClose}>editor-close</button>
<button type="button" onClick={() => p.onCreated(77)}>editor-created</button>
<button type="button" onClick={() => p.onRequestDelete(5)}>editor-delete</button>
</div>
),
}))
vi.mock('../components/Collections/LabelManager', () => ({
default: (p: { isOpen: boolean; onCreate: (n: string) => void; onUpdate: (id: number, b: Record<string, unknown>) => void; onDelete: (id: number) => void; onClose: () => void }) =>
p.isOpen ? (
<div data-testid="label-manager">
<button type="button" onClick={() => p.onCreate('Food')}>label-create</button>
<button type="button" onClick={() => p.onUpdate(1, { name: 'x' })}>label-update</button>
<button type="button" onClick={() => p.onDelete(1)}>label-delete</button>
<button type="button" onClick={p.onClose}>label-close</button>
</div>
) : null,
}))
vi.mock('../components/Collections/BulkAssignLabelModal', () => ({
default: (p: { isOpen: boolean; count: number; onAssign: (ids: number[]) => void; onManage: () => void; onClose: () => void }) =>
p.isOpen ? (
<div data-testid="bulk-labels">
<span data-testid="bulk-count">{p.count}</span>
<button type="button" onClick={() => p.onAssign([1])}>bulk-assign</button>
<button type="button" onClick={p.onManage}>bulk-manage</button>
<button type="button" onClick={p.onClose}>bulk-close</button>
</div>
) : null,
}))
vi.mock('../components/shared/Modal', () => ({
default: (p: { isOpen: boolean; title: string; onClose: () => void; children: React.ReactNode; footer: React.ReactNode }) =>
p.isOpen ? (
<div data-testid="confirm-modal">
<span>{p.title}</span>
<button type="button" onClick={p.onClose}>modal-dismiss</button>
{p.children}
{p.footer}
</div>
) : null,
}))
vi.mock('../components/shared/EmptyState', () => ({
default: (p: { scene: string; title: string }) => <div data-testid={`empty-${p.scene}`}>{p.title}</div>,
}))
const mockUseCollections = vi.fn()
vi.mock('./collections/useCollections', () => ({ useCollections: () => mockUseCollections() }))
type Hook = Record<string, unknown>
const noop = vi.fn(() => {})
function makeHook(overrides: Hook = {}): Hook {
const list = { id: 1, name: 'Japan', is_owner: true, color: '#6366f1', cover_image: null, description: 'trip ideas' }
return {
t: (k: string) => k,
language: 'en',
dark: false,
navigate: noop,
isWide: true,
heroRef: () => {},
heroHeight: 240,
listColRef: () => {},
listColRect: { left: 10, width: 400 },
categories: [],
collections: [list],
ownedLists: [list, { id: 4, name: 'Other', is_owner: true }],
sharedLists: [],
activeCollection: list,
isAllSaved: false,
isOwner: true,
myRole: 'owner',
canEdit: true,
canDelete: true,
canShare: true,
shareMemberCount: 2,
activeId: 1,
places: [{ id: 10 }],
visiblePlaces: [{ id: 10 }],
mappable: [{ id: 10 }],
members: [],
incomingInvites: [],
counts: { all: 1, idea: 0, want: 1, visited: 0 },
view: 'list',
statusFilter: 'all',
categoryFilter: 'all',
categoryOptions: [],
ratingFilter: 'all',
sortMode: 'default',
search: '',
selectedPlaceId: null,
selectMode: false,
selectedIds: [],
labels: [],
labelFilter: [],
labelOptions: [],
loading: false,
placesLoading: false,
setView: vi.fn(() => {}),
setStatusFilter: noop,
setCategoryFilter: noop,
setRatingFilter: noop,
setLabelFilter: noop,
setSortMode: noop,
setSearch: vi.fn(() => {}),
setSelectedPlaceId: vi.fn(() => {}),
setSelectMode: vi.fn(() => {}),
toggleSelect: noop,
updatePlace: vi.fn(() => {}),
uploadPlaceImage: vi.fn(() => {}),
showLabelManager: false,
setShowLabelManager: vi.fn(() => {}),
labelPickerOpen: false,
setLabelPickerOpen: vi.fn(() => {}),
handleCreateLabel: vi.fn(() => {}),
handleUpdateLabel: vi.fn(() => {}),
handleDeleteLabel: vi.fn(() => {}),
handleBulkAssignLabels: vi.fn(() => {}),
handleAssignPlaceLabels: noop,
editorTarget: null,
setEditorTarget: vi.fn(() => {}),
handleEditorCreated: vi.fn(() => {}),
showAddPlace: false,
setShowAddPlace: vi.fn(() => {}),
handlePlaceAdded: vi.fn(() => {}),
confirmDeleteList: null,
setConfirmDeleteList: vi.fn(() => {}),
mobileRailOpen: false,
setMobileRailOpen: vi.fn(() => {}),
showShare: false,
setShowShare: vi.fn(() => {}),
handleAfterLeave: vi.fn(() => {}),
selectedPlace: null,
detailPlace: null,
detailCategories: [],
handleCloseDetail: vi.fn(() => {}),
handleDetailStatus: vi.fn(() => {}),
handleDetailRemove: vi.fn(() => {}),
copyIds: null,
openCopyForSelectedPlace: vi.fn(() => {}),
openCopyForSelection: vi.fn(() => {}),
closeCopy: vi.fn(() => {}),
handleCopyToTrip: vi.fn(() => {}),
handleSelectList: vi.fn(() => {}),
handleDeleteList: vi.fn(() => {}),
handleStatusChange: vi.fn(() => {}),
handleRatePlace: vi.fn(() => {}),
handleDeletePlace: vi.fn(() => {}),
handleDeleteSelected: vi.fn(() => {}),
handleAcceptInvite: vi.fn(() => {}),
handleDeclineInvite: vi.fn(() => {}),
allVisibleSelected: false,
handleSelectAll: vi.fn(() => {}),
listPickerMode: null,
setListPickerMode: vi.fn(() => {}),
handleMoveToList: vi.fn(() => {}),
handleDuplicateToList: vi.fn(() => {}),
...overrides,
}
}
/** Render the page for a hook fixture and hand the fixture back for assertions. */
function renderPage(overrides: Hook = {}): Hook {
const hook = makeHook(overrides)
mockUseCollections.mockReturnValue(hook)
render(<CollectionsPage />)
return hook
}
beforeEach(() => {
isPhone = false
mockUseCollections.mockReset()
})
describe('CollectionsPage — shell', () => {
it('FE-PAGE-COLLPAGE-001: hands a phone viewport to the mobile screen', () => {
isPhone = true
mockUseCollections.mockReturnValue(makeHook())
render(<CollectionsPage />)
expect(screen.getByTestId('mobile-collections')).toBeInTheDocument()
expect(screen.queryByTestId('navbar')).toBeNull()
})
it('FE-PAGE-COLLPAGE-002: renders the desktop shell with hero, rail and list', () => {
renderPage()
expect(screen.getByTestId('navbar')).toBeInTheDocument()
expect(screen.getByTestId('rail')).toBeInTheDocument()
expect(screen.getByTestId('hero-title')).toHaveTextContent('Japan')
expect(screen.getByTestId('hero-eyebrow')).toHaveTextContent('collections.hero.mine')
expect(screen.getByTestId('list-count')).toHaveTextContent('1')
})
it('FE-PAGE-COLLPAGE-003: labels the All-saved union with its own title and eyebrow', () => {
renderPage({ isAllSaved: true, activeCollection: null, activeId: 'all' })
expect(screen.getByTestId('hero-title')).toHaveTextContent('collections.allSaved')
expect(screen.getByTestId('hero-eyebrow')).toHaveTextContent('collections.hero.all')
})
it('FE-PAGE-COLLPAGE-004: marks a shared list in the eyebrow and hides the edit affordance', () => {
renderPage({
activeCollection: { id: 1, name: 'Shared', is_owner: false },
isOwner: false,
myRole: 'editor',
})
expect(screen.getByTestId('hero-eyebrow')).toHaveTextContent('collections.hero.shared')
expect(screen.queryByText('hero-edit')).toBeNull()
})
it('FE-PAGE-COLLPAGE-005: falls back to the generic title when no list is active', () => {
renderPage({ activeCollection: null, activeId: null, isAllSaved: false })
expect(screen.getByTestId('hero-title')).toHaveTextContent('collections.title')
})
it('FE-PAGE-COLLPAGE-006: offers a first-list CTA when the user has no lists at all', () => {
const hook = renderPage({ collections: [], loading: false, places: [] })
expect(screen.getByTestId('empty-collections')).toHaveTextContent('collections.empty.firstTitle')
expect(screen.queryByTestId('hero')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: /collections.newList/ }))
expect(hook.setEditorTarget).toHaveBeenCalledWith('new')
})
it('FE-PAGE-COLLPAGE-007: shows a spinner while the first places load', () => {
renderPage({ places: [], visiblePlaces: [], mappable: [], placesLoading: true })
expect(document.querySelector('.col-spinner')).not.toBeNull()
expect(screen.queryByTestId('list')).toBeNull()
})
})
describe('CollectionsPage — body branches', () => {
it('FE-PAGE-COLLPAGE-008: an empty list shows the empty state plus the add CTA', () => {
const hook = renderPage({ places: [], visiblePlaces: [], mappable: [] })
expect(screen.getByTestId('empty-collections')).toHaveTextContent('collections.empty.title')
fireEvent.click(screen.getByRole('button', { name: /collections.addPlace/ }))
expect(hook.setShowAddPlace).toHaveBeenCalledWith(true)
})
it('FE-PAGE-COLLPAGE-009: a viewer on an empty list gets no add CTA', () => {
renderPage({ places: [], visiblePlaces: [], mappable: [], canEdit: false })
expect(screen.getByTestId('empty-collections')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /collections.addPlace/ })).toBeNull()
})
it('FE-PAGE-COLLPAGE-010: a wide layout with mappable places renders the split with an overlay map', () => {
renderPage()
expect(screen.getByTestId('map-overlay')).toBeInTheDocument()
expect(screen.getByTestId('list')).toBeInTheDocument()
// The map overlay owns the toolbar, so the page-level search box is gone.
expect(screen.queryByPlaceholderText('collections.search')).toBeNull()
})
it('FE-PAGE-COLLPAGE-011: a narrow layout in map view renders the standalone map', () => {
renderPage({ isWide: false, view: 'map' })
expect(screen.getByTestId('map-plain')).toBeInTheDocument()
expect(screen.queryByTestId('list')).toBeNull()
expect(screen.getByPlaceholderText('collections.search')).toBeInTheDocument()
})
it('FE-PAGE-COLLPAGE-012: a narrow layout in list view renders the plain list column', () => {
renderPage({ isWide: false })
expect(screen.getByTestId('list')).toBeInTheDocument()
expect(screen.queryByTestId('map-plain')).toBeNull()
expect(screen.queryByTestId('map-overlay')).toBeNull()
})
it('FE-PAGE-COLLPAGE-013: places without coordinates keep the list column even on a wide layout', () => {
renderPage({ mappable: [] })
expect(screen.getByTestId('list')).toBeInTheDocument()
expect(screen.queryByTestId('map-overlay')).toBeNull()
})
it('FE-PAGE-COLLPAGE-014: a filter that matches nothing keeps the filter bar and shows the no-match state', () => {
renderPage({ visiblePlaces: [], mappable: [] })
expect(screen.getByTestId('filterbar')).toBeInTheDocument()
expect(screen.getByTestId('empty-search')).toHaveTextContent('collections.empty.noMatchTitle')
expect(screen.queryByTestId('list')).toBeNull()
})
})
describe('CollectionsPage — toolbar', () => {
it('FE-PAGE-COLLPAGE-015: the view segment toggles between list and map below the split breakpoint', () => {
const hook = renderPage({ isWide: false })
fireEvent.click(screen.getByRole('button', { name: 'collections.view.map' }))
expect(hook.setView).toHaveBeenCalledWith('map')
fireEvent.click(screen.getByRole('button', { name: 'collections.view.list' }))
expect(hook.setView).toHaveBeenCalledWith('list')
})
it('FE-PAGE-COLLPAGE-016: the search box feeds the store', () => {
const hook = renderPage({ isWide: false })
fireEvent.change(screen.getByPlaceholderText('collections.search'), { target: { value: 'ramen' } })
expect(hook.setSearch).toHaveBeenCalledWith('ramen')
})
it('FE-PAGE-COLLPAGE-017: the rail toggle opens the mobile drawer, which closes again', () => {
const hook = renderPage({ isWide: false })
fireEvent.click(screen.getByRole('button', { name: /collections.title/ }))
expect(hook.setMobileRailOpen).toHaveBeenCalledWith(true)
})
it('FE-PAGE-COLLPAGE-018: the open drawer renders a second rail and closes on the backdrop', () => {
const hook = renderPage({ mobileRailOpen: true })
expect(screen.getAllByTestId('rail')).toHaveLength(2)
fireEvent.click(screen.getByRole('button', { name: 'common.close' }))
expect(hook.setMobileRailOpen).toHaveBeenCalledWith(false)
const backdrop = document.querySelector('.col-drawer-backdrop')
fireEvent.click(backdrop as Element)
expect(hook.setMobileRailOpen).toHaveBeenCalledTimes(2)
})
})
describe('CollectionsPage — select mode', () => {
const selecting = { selectMode: true, selectedIds: [10, 11] }
it('FE-PAGE-COLLPAGE-019: the select bar exposes every bulk action to an owner', () => {
const hook = renderPage(selecting)
expect(screen.getByText('collections.selectedCount')).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: /collections.selectAll/ }))
expect(hook.handleSelectAll).toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: /collections.labels.assign/ }))
expect(hook.setLabelPickerOpen).toHaveBeenCalledWith(true)
fireEvent.click(screen.getByRole('button', { name: /collections.moveToList/ }))
expect(hook.setListPickerMode).toHaveBeenCalledWith('move')
fireEvent.click(screen.getByRole('button', { name: /collections.duplicateToList/ }))
expect(hook.setListPickerMode).toHaveBeenCalledWith('copy')
fireEvent.click(screen.getByRole('button', { name: /collections.copyToTrip/ }))
expect(hook.openCopyForSelection).toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: /common.delete/ }))
expect(hook.handleDeleteSelected).toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'common.cancel' }))
expect(hook.setSelectMode).toHaveBeenCalledWith(false)
})
it('FE-PAGE-COLLPAGE-020: the select-all button flips to deselect once everything is selected', () => {
renderPage({ ...selecting, allVisibleSelected: true })
expect(screen.getByRole('button', { name: /collections.deselectAll/ })).toBeInTheDocument()
expect(screen.queryByRole('button', { name: /collections.selectAll/ })).toBeNull()
})
it('FE-PAGE-COLLPAGE-021: a viewer only keeps the non-mutating bulk actions', () => {
renderPage({ ...selecting, canEdit: false, canDelete: false })
expect(screen.queryByRole('button', { name: /collections.moveToList/ })).toBeNull()
expect(screen.queryByRole('button', { name: /collections.labels.assign/ })).toBeNull()
expect(screen.queryByRole('button', { name: /common.delete/ })).toBeNull()
expect(screen.getByRole('button', { name: /collections.duplicateToList/ })).toBeInTheDocument()
expect(screen.getByRole('button', { name: /collections.copyToTrip/ })).toBeInTheDocument()
})
it('FE-PAGE-COLLPAGE-022: bulk buttons are disabled while nothing is selected', () => {
renderPage({ selectMode: true, selectedIds: [] })
expect(screen.getByRole('button', { name: /collections.moveToList/ })).toBeDisabled()
expect(screen.getByRole('button', { name: /collections.copyToTrip/ })).toBeDisabled()
expect(screen.getByRole('button', { name: /common.delete/ })).toBeDisabled()
})
it('FE-PAGE-COLLPAGE-023: the All-saved union hides the label bulk action', () => {
renderPage({ ...selecting, isAllSaved: true, activeId: 'all', activeCollection: null })
expect(screen.queryByRole('button', { name: /collections.labels.assign/ })).toBeNull()
expect(screen.getByRole('button', { name: /collections.moveToList/ })).toBeInTheDocument()
})
})
describe('CollectionsPage — child wiring', () => {
it('FE-PAGE-COLLPAGE-024: the rail forwards select, new-list and invite actions', () => {
const hook = renderPage()
fireEvent.click(screen.getByText('rail-select'))
expect(hook.handleSelectList).toHaveBeenCalledWith(2)
fireEvent.click(screen.getByText('rail-new'))
expect(hook.setMobileRailOpen).toHaveBeenCalledWith(false)
expect(hook.setEditorTarget).toHaveBeenCalledWith('new')
fireEvent.click(screen.getByText('rail-accept'))
expect(hook.handleAcceptInvite).toHaveBeenCalledWith(3)
fireEvent.click(screen.getByText('rail-decline'))
expect(hook.handleDeclineInvite).toHaveBeenCalledWith(3)
})
it('FE-PAGE-COLLPAGE-025: the hero forwards edit and share', () => {
const list = { id: 1, name: 'Japan', is_owner: true }
const hook = renderPage({ activeCollection: list })
fireEvent.click(screen.getByText('hero-edit'))
expect(hook.setEditorTarget).toHaveBeenCalledWith(list)
fireEvent.click(screen.getByText('hero-share'))
expect(hook.setShowShare).toHaveBeenCalledWith(true)
})
it('FE-PAGE-COLLPAGE-026: opening a place toggles the selection, and re-opening clears it', () => {
const hook = renderPage()
fireEvent.click(screen.getByText('list-open'))
expect(hook.setSelectedPlaceId).toHaveBeenCalledWith(10)
const open = renderPage({ selectedPlaceId: 10 })
fireEvent.click(screen.getAllByText('list-open')[1])
expect(open.setSelectedPlaceId).toHaveBeenCalledWith(null)
})
it('FE-PAGE-COLLPAGE-027: the map deselects, searches and toggles back to the list', () => {
const hook = renderPage()
fireEvent.click(screen.getByText('map-deselect'))
expect(hook.setSelectedPlaceId).toHaveBeenCalledWith(null)
fireEvent.click(screen.getByText('map-search'))
expect(hook.setSearch).toHaveBeenCalledWith('cafe')
// From the list view the toggle closes the detail sheet and switches to map.
fireEvent.click(screen.getByText('map-toggle'))
expect(hook.setSelectedPlaceId).toHaveBeenCalledWith(null)
expect(hook.setView).toHaveBeenCalledWith('map')
})
it('FE-PAGE-COLLPAGE-028: from the map view a marker click drops back into the split', () => {
const hook = renderPage({ view: 'map' })
fireEvent.click(screen.getByText('map-select'))
expect(hook.setSelectedPlaceId).toHaveBeenCalledWith(10)
expect(hook.setView).toHaveBeenCalledWith('list')
})
it('FE-PAGE-COLLPAGE-029: the map view toggle returns to the list without clearing the selection', () => {
const hook = renderPage({ view: 'map' })
fireEvent.click(screen.getByText('map-toggle'))
expect(hook.setView).toHaveBeenCalledWith('list')
expect(hook.setSelectedPlaceId).not.toHaveBeenCalled()
})
it('FE-PAGE-COLLPAGE-030: the filter bar drives add-place, label management and select mode', () => {
const hook = renderPage()
expect(screen.getByTestId('filter-flags')).toHaveTextContent('true|true|true')
fireEvent.click(screen.getByText('filter-add'))
expect(hook.setShowAddPlace).toHaveBeenCalledWith(true)
fireEvent.click(screen.getByText('filter-labels'))
expect(hook.setShowLabelManager).toHaveBeenCalledWith(true)
fireEvent.click(screen.getByText('filter-select'))
expect(hook.setSelectMode).toHaveBeenCalledWith(true)
})
it('FE-PAGE-COLLPAGE-031: the All-saved union has no labels and no add button in the filter row', () => {
renderPage({ isAllSaved: true, activeId: 'all', activeCollection: null })
expect(screen.getByTestId('filter-flags')).toHaveTextContent('false|false|true')
expect(screen.queryByText('filter-add')).toBeNull()
})
})
describe('CollectionsPage — detail sheet and modals', () => {
const withPlace = { selectedPlace: { id: 10, name: 'Bar' }, selectedPlaceId: 10 }
it('FE-PAGE-COLLPAGE-032: the detail sheet docks over the list column on the split', () => {
const hook = renderPage(withPlace)
expect(screen.getByTestId('detail-anchored')).toHaveTextContent('docked')
fireEvent.click(screen.getByText('detail-close'))
expect(hook.handleCloseDetail).toHaveBeenCalled()
fireEvent.click(screen.getByText('detail-status'))
expect(hook.handleDetailStatus).toHaveBeenCalledWith('visited')
fireEvent.click(screen.getByText('detail-save'))
expect(hook.updatePlace).toHaveBeenCalledWith(10, { notes: 'hi' })
fireEvent.click(screen.getByText('detail-upload'))
expect(hook.uploadPlaceImage).toHaveBeenCalledWith(10, expect.any(File))
fireEvent.click(screen.getByText('detail-copy'))
expect(hook.openCopyForSelectedPlace).toHaveBeenCalled()
fireEvent.click(screen.getByText('detail-remove'))
expect(hook.handleDetailRemove).toHaveBeenCalled()
fireEvent.click(screen.getByText('detail-rate'))
expect(hook.handleRatePlace).toHaveBeenCalledWith(10, 4)
})
it('FE-PAGE-COLLPAGE-033: without a split the detail is a full-width sheet', () => {
renderPage({ ...withPlace, isWide: false })
expect(screen.getByTestId('detail-anchored')).toHaveTextContent('sheet')
})
it('FE-PAGE-COLLPAGE-034: the full-map view hides the detail sheet', () => {
renderPage({ ...withPlace, view: 'map', isWide: false })
expect(screen.queryByTestId('detail')).toBeNull()
})
it('FE-PAGE-COLLPAGE-035: the add-place modal is bound to the active list', () => {
const hook = renderPage({ showAddPlace: true })
expect(screen.getByTestId('addplace-modal')).toHaveTextContent('1')
fireEvent.click(screen.getByText('addplace-added'))
expect(hook.handlePlaceAdded).toHaveBeenCalled()
fireEvent.click(screen.getByText('addplace-close'))
expect(hook.setShowAddPlace).toHaveBeenCalledWith(false)
})
it('FE-PAGE-COLLPAGE-036: the All-saved union has no add-place modal', () => {
renderPage({ showAddPlace: true, isAllSaved: true, activeId: 'all', activeCollection: null })
expect(screen.queryByTestId('addplace-modal')).toBeNull()
})
it('FE-PAGE-COLLPAGE-037: the copy-to-trip modal opens with the pending ids', () => {
const hook = renderPage({ copyIds: [10, 11] })
expect(screen.getByTestId('copy-modal')).toHaveTextContent('10,11')
fireEvent.click(screen.getByText('copy-close'))
expect(hook.closeCopy).toHaveBeenCalled()
})
it('FE-PAGE-COLLPAGE-038: the list picker in move mode excludes the current list', () => {
const hook = renderPage({ listPickerMode: 'move', selectedIds: [10] })
expect(screen.getByTestId('move-mode')).toHaveTextContent('move')
expect(screen.getByTestId('move-lists')).toHaveTextContent('4')
fireEvent.click(screen.getByText('move-pick'))
expect(hook.handleMoveToList).toHaveBeenCalledWith(9)
fireEvent.click(screen.getByText('move-close'))
expect(hook.setListPickerMode).toHaveBeenCalledWith(null)
})
it('FE-PAGE-COLLPAGE-039: the list picker in copy mode duplicates instead', () => {
const hook = renderPage({ listPickerMode: 'copy', selectedIds: [10] })
fireEvent.click(screen.getByText('move-pick'))
expect(hook.handleDuplicateToList).toHaveBeenCalledWith(9)
expect(hook.handleMoveToList).not.toHaveBeenCalled()
})
it('FE-PAGE-COLLPAGE-040: the share modal closes and reports a leave', () => {
const hook = renderPage({ showShare: true })
fireEvent.click(screen.getByText('share-leave'))
expect(hook.handleAfterLeave).toHaveBeenCalled()
fireEvent.click(screen.getByText('share-close'))
expect(hook.setShowShare).toHaveBeenCalledWith(false)
})
it('FE-PAGE-COLLPAGE-041: a list that cannot be shared renders no share modal', () => {
renderPage({ showShare: true, canShare: false })
expect(screen.queryByTestId('share-modal')).toBeNull()
})
it('FE-PAGE-COLLPAGE-042: the list editor forwards create, close and delete requests', () => {
const hook = renderPage()
fireEvent.click(screen.getByText('editor-created'))
expect(hook.handleEditorCreated).toHaveBeenCalledWith(77)
fireEvent.click(screen.getByText('editor-delete'))
expect(hook.setConfirmDeleteList).toHaveBeenCalledWith(5)
fireEvent.click(screen.getByText('editor-close'))
expect(hook.setEditorTarget).toHaveBeenCalledWith(null)
})
it('FE-PAGE-COLLPAGE-043: the label manager forwards its CRUD callbacks', () => {
const hook = renderPage({ showLabelManager: true })
fireEvent.click(screen.getByText('label-create'))
expect(hook.handleCreateLabel).toHaveBeenCalledWith('Food')
fireEvent.click(screen.getByText('label-update'))
expect(hook.handleUpdateLabel).toHaveBeenCalledWith(1, { name: 'x' })
fireEvent.click(screen.getByText('label-delete'))
expect(hook.handleDeleteLabel).toHaveBeenCalledWith(1)
fireEvent.click(screen.getByText('label-close'))
expect(hook.setShowLabelManager).toHaveBeenCalledWith(false)
})
it('FE-PAGE-COLLPAGE-044: the bulk label picker can hand over to the manager', () => {
const hook = renderPage({ labelPickerOpen: true, selectedIds: [10, 11] })
expect(screen.getByTestId('bulk-count')).toHaveTextContent('2')
fireEvent.click(screen.getByText('bulk-assign'))
expect(hook.handleBulkAssignLabels).toHaveBeenCalledWith([1])
fireEvent.click(screen.getByText('bulk-manage'))
expect(hook.setLabelPickerOpen).toHaveBeenCalledWith(false)
expect(hook.setShowLabelManager).toHaveBeenCalledWith(true)
fireEvent.click(screen.getByText('bulk-close'))
expect(hook.setLabelPickerOpen).toHaveBeenLastCalledWith(false)
})
it('FE-PAGE-COLLPAGE-045: label modals are absent for someone who cannot manage labels', () => {
renderPage({ showLabelManager: true, labelPickerOpen: true, canEdit: false })
expect(screen.queryByTestId('label-manager')).toBeNull()
expect(screen.queryByTestId('bulk-labels')).toBeNull()
})
it('FE-PAGE-COLLPAGE-046: the delete-list confirmation runs the handler', () => {
const hook = renderPage({ confirmDeleteList: 5 })
expect(screen.getByTestId('confirm-modal')).toHaveTextContent('collections.deleteListConfirm')
fireEvent.click(screen.getByRole('button', { name: 'common.delete' }))
expect(hook.handleDeleteList).toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'common.cancel' }))
expect(hook.setConfirmDeleteList).toHaveBeenCalledWith(null)
// Dismissing the modal itself (backdrop / escape) clears the pending id too.
fireEvent.click(screen.getByText('modal-dismiss'))
expect(hook.setConfirmDeleteList).toHaveBeenCalledTimes(2)
})
it('FE-PAGE-COLLPAGE-047: no confirmation is rendered without a pending delete', () => {
renderPage()
expect(screen.queryByTestId('confirm-modal')).toBeNull()
})
})
@@ -0,0 +1,388 @@
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { http, HttpResponse } from 'msw';
import { act } from '@testing-library/react';
import { render, screen, fireEvent, waitFor, within } from '../../tests/helpers/render';
import { server } from '../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../tests/helpers/store';
import { buildUser, buildTrip, buildSettings } from '../../tests/helpers/factories';
import { useAuthStore } from '../store/authStore';
import { useSettingsStore } from '../store/settingsStore';
import { useAddonStore } from '../store/addonStore';
import { usePluginStore } from '../store/pluginStore';
import DashboardPage from './DashboardPage';
// FE-PAGE-DESKDASH-001 onwards
type MqListener = (e: MediaQueryListEvent) => void;
const mqListeners = new Map<string, Set<MqListener>>();
let phone = false;
function installMatchMedia(): void {
mqListeners.clear();
phone = false;
Object.defineProperty(window, 'matchMedia', {
writable: true,
configurable: true,
value: (query: string) => ({
get matches() { return phone; },
media: query,
onchange: null,
addListener: () => {},
removeListener: () => {},
addEventListener: (_type: string, listener: MqListener) => {
if (!mqListeners.has(query)) mqListeners.set(query, new Set());
mqListeners.get(query)?.add(listener);
},
removeEventListener: (_type: string, listener: MqListener) => {
mqListeners.get(query)?.delete(listener);
},
dispatchEvent: () => true,
}),
});
}
function setPhone(next: boolean): void {
phone = next;
mqListeners.forEach(set => set.forEach(l => l({ matches: next } as MediaQueryListEvent)));
}
const TRIP = buildTrip({ id: 101, title: 'Paris Adventure', start_date: '2026-07-01', end_date: '2026-07-10' });
function onlyTrips(trips: unknown[]) {
server.use(
http.get('/api/trips', ({ request }) => {
const url = new URL(request.url);
return HttpResponse.json({ trips: url.searchParams.get('archived') ? [] : trips });
}),
);
}
function stats(body: Record<string, unknown>) {
server.use(http.get('/api/auth/travel-stats', () => HttpResponse.json(body)));
}
function appearance(dashboard: Record<string, unknown>) {
seedStore(useSettingsStore, { settings: buildSettings({ appearance: { dashboard } } as never) });
}
beforeEach(() => {
// Pinned inside the fixture trip's window so the spotlight/grid split is stable.
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.setSystemTime(new Date('2026-07-05T12:00:00Z'));
installMatchMedia();
resetAllStores();
seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });
usePluginStore.setState({ plugins: [], loaded: true });
onlyTrips([TRIP]);
stats({ totalTrips: 3, totalDays: 21, totalPlaces: 9, totalDistanceKm: 0, countries: [] });
server.use(
http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([
{ date: '2026-07-01', base: 'EUR', quote: 'USD', rate: 1.1 },
])),
http.get('/api/reservations/upcoming', () => HttpResponse.json({ reservations: [] })),
http.get('/api/addons/collections', () => HttpResponse.json({ collections: [] })),
http.get('/api/trips/:id/bundle', () => HttpResponse.json({ members: [], places: [] })),
);
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
const distanceValue = () =>
document.querySelectorAll('.atlas-card .value')[document.querySelectorAll('.atlas-card').length - 1];
describe('DashboardPage (desktop)', () => {
it('FE-PAGE-DESKDASH-001: a four-digit distance collapses to a compact k value', async () => {
stats({ totalTrips: 1, totalDays: 1, totalPlaces: 1, totalDistanceKm: 12345, countries: [] });
seedStore(useSettingsStore, { settings: buildSettings({ distance_unit: 'metric' }) });
render(<DashboardPage />);
await waitFor(() => expect(screen.getByText('12.3k')).toBeInTheDocument());
});
it('FE-PAGE-DESKDASH-002: a sub-0.1 distance is reported as "<0.1"', async () => {
stats({ totalTrips: 1, totalDays: 1, totalPlaces: 1, totalDistanceKm: 0.02, countries: [] });
seedStore(useSettingsStore, { settings: buildSettings({ distance_unit: 'metric' }) });
render(<DashboardPage />);
await waitFor(() => expect(screen.getByText('<0.1')).toBeInTheDocument());
});
it('FE-PAGE-DESKDASH-003: a negative distance is clamped to zero', async () => {
stats({ totalTrips: 1, totalDays: 1, totalPlaces: 1, totalDistanceKm: -40, countries: [] });
seedStore(useSettingsStore, { settings: buildSettings({ distance_unit: 'metric' }) });
render(<DashboardPage />);
await waitFor(() => expect(distanceValue()?.textContent).toContain('0'));
expect(screen.queryByText('<0.1')).not.toBeInTheDocument();
});
it('FE-PAGE-DESKDASH-004: more than five countries collapse into an overflow flag', async () => {
stats({ totalTrips: 1, totalDays: 1, totalPlaces: 1, totalDistanceKm: 0, countries: ['fr', 'de', 'it', 'es', 'pt', 'nl', 'be'] });
render(<DashboardPage />);
await waitFor(() => expect(screen.getByText('+2')).toBeInTheDocument());
expect(screen.getAllByRole('img', { name: 'fr' })[0]).toHaveAttribute('src', 'https://flagcdn.com/w40/fr.png');
});
it('FE-PAGE-DESKDASH-005: the whole atlas row disappears when every tile is off', async () => {
appearance({
desktop: { sidebar: true, currency: true, collections: false, timezones: true, upcomingReservations: true, atlas: false, tripsTotal: false, daysTraveled: false, distanceFlown: false },
});
const { container } = render(<DashboardPage />);
await waitFor(() => expect(screen.getAllByText('Paris Adventure').length).toBeGreaterThan(0));
expect(container.querySelector('.atlas')).toBeNull();
});
it('FE-PAGE-DESKDASH-006: the sidebar disappears when none of its widgets are on', async () => {
appearance({
desktop: { sidebar: true, currency: false, collections: false, timezones: false, upcomingReservations: false, atlas: true, tripsTotal: true, daysTraveled: true, distanceFlown: true },
});
const { container } = render(<DashboardPage />);
await waitFor(() => expect(screen.getAllByText('Paris Adventure').length).toBeGreaterThan(0));
expect(container.querySelector('.page-sidebar')).toBeNull();
expect(container.querySelector('main')).toHaveAttribute('data-no-sidebar', 'true');
});
it('FE-PAGE-DESKDASH-007: the collections widget needs the addon and the flag', async () => {
// The store reloads its addons on mount, so the gate has to come from the API too.
server.use(http.get('/api/addons', () => HttpResponse.json({
bagTracking: false,
addons: [{ id: 'collections', name: 'Collections', type: 'feature', icon: 'bookmark', enabled: true }],
})));
useAddonStore.setState({
addons: [{ id: 'collections', name: 'Collections', type: 'feature', icon: 'bookmark', enabled: true }],
loaded: true,
} as never);
server.use(http.get('/api/addons/collections', () =>
HttpResponse.json({ collections: [{ id: 1, name: 'Tokyo eats', color: '#f00', cover_image: null, place_count: 4 }] })));
render(<DashboardPage />);
expect(await screen.findByText('Tokyo eats')).toBeInTheDocument();
});
it('FE-PAGE-DESKDASH-008: the upcoming tool lists reservations and opens their trip', async () => {
seedStore(useSettingsStore, { settings: buildSettings({ time_format: '24h' }) });
server.use(http.get('/api/reservations/upcoming', () => HttpResponse.json({
reservations: [
{ id: 1, trip_id: 101, title: 'Louvre', type: 'flight', reservation_time: '2026-09-03T19:30:00', location: 'Paris' },
{ id: 2, trip_id: 101, title: 'Hotel Ibis', type: 'hotel', reservation_time: null, day_date: null, trip_title: 'Paris Adventure' },
],
})));
const { container } = render(<DashboardPage />);
expect(await screen.findByText('Louvre')).toBeInTheDocument();
expect(screen.getByText('19:30', { exact: false })).toBeInTheDocument();
// A reservation with no date at all still renders, with a dash for the day.
expect(within(container.querySelector('.upc-list') as HTMLElement).getByText('–')).toBeInTheDocument();
fireEvent.click(screen.getByText('Louvre'));
expect(screen.getByText('Hotel Ibis')).toBeInTheDocument();
});
it('FE-PAGE-DESKDASH-009: the currency tool converts and swaps the pair', async () => {
seedStore(useSettingsStore, { settings: buildSettings({ dashboard_fx_from: 'EUR', dashboard_fx_to: 'USD' }) });
const { container } = render(<DashboardPage />);
await waitFor(() => expect(screen.getByText('1 EUR = 1.1000 USD')).toBeInTheDocument());
const amount = container.querySelector('.fx-field .amt') as HTMLInputElement;
fireEvent.change(amount, { target: { value: '50' } });
expect(container.querySelectorAll('.fx-field .amt')[1]).toHaveValue('55.00');
fireEvent.click(screen.getByRole('button', { name: 'Swap currencies' }));
await waitFor(() => expect(useSettingsStore.getState().settings.dashboard_fx_from).toBe('USD'));
});
it('FE-PAGE-DESKDASH-010: the timezone tool removes a zone and reports the empty list', async () => {
seedStore(useSettingsStore, { settings: buildSettings({ dashboard_timezones: ['Asia/Tokyo'] }) });
render(<DashboardPage />);
await waitFor(() => expect(screen.getByText('Tokyo')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: 'Remove Tokyo' }));
await waitFor(() => expect(screen.getByText('No other timezones yet — add one with +')).toBeInTheDocument());
});
it('FE-PAGE-DESKDASH-011: the timezone tool opens a picker and adds the chosen zone', async () => {
seedStore(useSettingsStore, { settings: buildSettings({ dashboard_timezones: ['Asia/Tokyo'] }) });
render(<DashboardPage />);
await waitFor(() => expect(screen.getByText('Tokyo')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: 'Add timezone' }));
// The picker shows its placeholder until a zone is chosen.
expect(screen.getByText('Search timezone…')).toBeInTheDocument();
});
it('FE-PAGE-DESKDASH-012: the boarding pass shows buddies, an overflow badge and places', async () => {
server.use(http.get('/api/trips/:id/bundle', () => HttpResponse.json({
members: [
{ id: 1, username: 'Maurice Boe', avatar_url: '/uploads/avatars/1.jpg' },
{ id: 2, username: 'Julien' },
{ id: 3, username: 'Ada Lovelace' },
{ id: 4, username: 'Bo' },
{ id: 5, username: 'Eve' },
],
places: [
{ id: 1, name: 'Louvre', image_url: null, lat: 1, lng: 2, google_place_id: null, osm_id: null },
{ id: 2, name: 'Eiffel', image_url: null, lat: 1, lng: 2, google_place_id: null, osm_id: null },
{ id: 3, name: 'Orsay', image_url: null, lat: 1, lng: 2, google_place_id: null, osm_id: null },
{ id: 4, name: 'Sacre', image_url: null, lat: 1, lng: 2, google_place_id: null, osm_id: null },
],
})));
const { container } = render(<DashboardPage />);
await waitFor(() => expect(container.querySelector('.buddy-more')).toHaveTextContent('+1'));
expect(screen.getByAltText('Maurice Boe')).toBeInTheDocument();
expect(screen.getByText('JU')).toBeInTheDocument();
expect(screen.getByText('AL')).toBeInTheDocument();
expect(container.querySelectorAll('.place-more')[0]).toHaveTextContent('+1');
});
it('FE-PAGE-DESKDASH-013: an empty bundle falls back to the owner initials and a pin', async () => {
const { container } = render(<DashboardPage />);
await waitFor(() => expect(container.querySelector('.buddy-avatar')).toBeInTheDocument());
expect(container.querySelector('.place-more .lucide-map-pin')).toBeInTheDocument();
});
it('FE-PAGE-DESKDASH-014: a hero-slot plugin frames itself over the boarding pass', async () => {
usePluginStore.setState({
plugins: [{ id: 'h1', name: 'Hero widget', type: 'widget', icon: null, slot: 'hero' }] as never,
loaded: true,
});
const { container } = render(<DashboardPage />);
await waitFor(() => expect(container.querySelector('.hero-pass-overlay')).toBeInTheDocument());
});
it('FE-PAGE-DESKDASH-015: opening the hero pass navigates to the trip', async () => {
const { container } = render(<DashboardPage />);
await waitFor(() => expect(container.querySelector('.hero-pass')).toBeInTheDocument());
fireEvent.click(container.querySelector('.hero-pass') as HTMLElement);
expect(screen.getAllByText('Paris Adventure').length).toBeGreaterThan(0);
});
it('FE-PAGE-DESKDASH-016: a trip card without dates says the dates are open', async () => {
onlyTrips([TRIP, buildTrip({ id: 102, title: 'Someday Iceland', start_date: null, end_date: null })]);
render(<DashboardPage />);
expect(await screen.findByText('Open dates')).toBeInTheDocument();
});
it('FE-PAGE-DESKDASH-018: a malformed date renders a dash rather than crashing', async () => {
onlyTrips([TRIP, buildTrip({ id: 103, title: 'Broken Dates', start_date: '2027-03-01', end_date: 'oops' })]);
const { container } = render(<DashboardPage />);
await screen.findByText('Broken Dates');
const card = screen.getByText('Broken Dates').closest('.trip-card') as HTMLElement;
expect(within(card).getByText('Open dates')).toBeInTheDocument();
expect(container.querySelector('.trips')).toBeInTheDocument();
});
it('FE-PAGE-DESKDASH-019: the grid card actions edit, duplicate and delete the trip', async () => {
onlyTrips([TRIP, buildTrip({ id: 104, title: 'Berlin', start_date: '2027-03-01', end_date: '2027-03-05' })]);
render(<DashboardPage />);
const card = (await screen.findByText('Berlin')).closest('.trip-card') as HTMLElement;
fireEvent.click(within(card).getByRole('button', { name: 'Duplicate' }));
expect(await screen.findByRole('button', { name: 'Copy trip' })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
fireEvent.click(within(card).getByRole('button', { name: 'Edit' }));
expect(await screen.findByDisplayValue('Berlin')).toBeInTheDocument();
});
it('FE-PAGE-DESKDASH-020: the grid card delete opens the confirm dialog', async () => {
onlyTrips([TRIP, buildTrip({ id: 104, title: 'Berlin', start_date: '2027-03-01', end_date: '2027-03-05' })]);
render(<DashboardPage />);
const card = (await screen.findByText('Berlin')).closest('.trip-card') as HTMLElement;
fireEvent.click(within(card).getByRole('button', { name: 'Delete' }));
expect(await screen.findByRole('button', { name: 'Cancel' })).toBeInTheDocument();
});
it('FE-PAGE-DESKDASH-021: the floating action button opens a blank trip form', async () => {
const { container } = render(<DashboardPage />);
await waitFor(() => expect(screen.getAllByText('Paris Adventure').length).toBeGreaterThan(0));
fireEvent.click(container.querySelector('.fab-new-trip') as HTMLElement);
expect(await screen.findByPlaceholderText('e.g. Summer in Japan')).toHaveValue('');
});
it('FE-PAGE-DESKDASH-022: the all-trips subscribe dialog opens and closes', async () => {
render(<DashboardPage />);
await waitFor(() => expect(screen.getAllByText('Paris Adventure').length).toBeGreaterThan(0));
fireEvent.click(screen.getByRole('button', { name: 'Subscribe to all trips calendar' }));
const description = await screen.findByText(/One calendar feed for all your active trips/);
fireEvent.click((description.parentElement as HTMLElement).querySelector('button') as HTMLElement);
await waitFor(() =>
expect(screen.queryByText(/One calendar feed for all your active trips/)).not.toBeInTheDocument());
});
it('FE-PAGE-DESKDASH-023: a non-array rate response leaves the converter unavailable', async () => {
server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json({ error: 'nope' })));
render(<DashboardPage />);
await waitFor(() => expect(screen.getByText('Rate unavailable')).toBeInTheDocument());
});
it('FE-PAGE-DESKDASH-024: a failed rate request leaves the converter unavailable', async () => {
server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.error()));
render(<DashboardPage />);
await waitFor(() => expect(screen.getByText('Rate unavailable')).toBeInTheDocument());
});
it('FE-PAGE-DESKDASH-025: a non-array legacy timezone value is dropped', async () => {
localStorage.setItem('trek_dashboard_tz', JSON.stringify({ tz: 'Asia/Tokyo' }));
seedStore(useSettingsStore, { settings: buildSettings(), isLoaded: true });
render(<DashboardPage />);
await waitFor(() => expect(localStorage.getItem('trek_dashboard_tz')).toBeNull());
expect(useSettingsStore.getState().settings.dashboard_timezones).toBeUndefined();
});
it('FE-PAGE-DESKDASH-026: a browser without Intl.supportedValuesOf falls back to a fixed zone list', async () => {
const intl = Intl as unknown as { supportedValuesOf?: (k: string) => string[] };
const original = intl.supportedValuesOf;
intl.supportedValuesOf = () => { throw new Error('unsupported'); };
seedStore(useSettingsStore, { settings: buildSettings({ dashboard_timezones: ['Asia/Tokyo'] }) });
try {
render(<DashboardPage />);
await waitFor(() => expect(screen.getByText('Tokyo')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: 'Add timezone' }));
expect(screen.getByText('Search timezone…')).toBeInTheDocument();
} finally {
intl.supportedValuesOf = original;
}
});
it('FE-PAGE-DESKDASH-017: crossing the phone breakpoint swaps in the mobile dashboard', async () => {
const { container } = render(<DashboardPage />);
await waitFor(() => expect(screen.getAllByText('Paris Adventure').length).toBeGreaterThan(0));
expect(container.querySelector('.trek-dash')).toBeInTheDocument();
act(() => { setPhone(true); });
await waitFor(() => expect(container.querySelector('.trek-dash')).toBeNull());
expect(screen.getByRole('button', { name: 'TREK' })).toBeInTheDocument();
});
});
@@ -0,0 +1,127 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import type { FormEvent } from 'react'
import { render, screen, fireEvent } from '../../tests/helpers/render'
import ForgotPasswordPage from './ForgotPasswordPage'
// FE-PAGE-FORGOTUI-001 to FE-PAGE-FORGOTUI-008
//
// ForgotPasswordPage is a wiring container over useForgotPassword (covered in
// forgotPassword/useForgotPassword.test.ts). The hook is mocked so the form,
// the sent screen and the SMTP hint can each be rendered on demand.
const mocks = vi.hoisted(() => ({ forgot: {} as Record<string, unknown> }))
vi.mock('./forgotPassword/useForgotPassword', () => ({ useForgotPassword: () => mocks.forgot }))
const navigate = vi.fn((_to: string) => {})
const setEmail = vi.fn((_v: string) => {})
const handleSubmit = vi.fn(async (_e: FormEvent) => {})
function setForgot(over: Record<string, unknown> = {}) {
mocks.forgot = {
navigate,
email: '',
setEmail,
submitted: false,
isLoading: false,
smtpConfigured: true,
handleSubmit,
...over,
}
}
beforeEach(() => {
vi.clearAllMocks()
setForgot()
})
describe('ForgotPasswordPage', () => {
it('FE-PAGE-FORGOTUI-001: renders the request form and the back link', () => {
setForgot()
render(<ForgotPasswordPage />)
expect(screen.getByRole('heading', { name: 'Reset your password' })).toBeInTheDocument()
expect(screen.getByText('Email')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Send reset link' })).toBeEnabled()
fireEvent.click(screen.getByRole('button', { name: 'Back to sign in' }))
expect(navigate).toHaveBeenCalledWith('/login')
})
it('FE-PAGE-FORGOTUI-002: typing an address is reported upwards', () => {
setForgot({ email: 'a@b.de' })
render(<ForgotPasswordPage />)
const input = screen.getByPlaceholderText('your@email.com')
expect(input).toHaveValue('a@b.de')
fireEvent.change(input, { target: { value: 'a@b.dev' } })
expect(setEmail).toHaveBeenCalledWith('a@b.dev')
})
it('FE-PAGE-FORGOTUI-003: focusing and blurring the field swaps its border colour', () => {
setForgot()
render(<ForgotPasswordPage />)
const input = screen.getByPlaceholderText('your@email.com') as HTMLInputElement
fireEvent.focus(input)
expect(input.style.borderColor).toBe('rgb(17, 24, 39)')
fireEvent.blur(input)
expect(input.style.borderColor).toBe('rgb(229, 231, 235)')
})
it('FE-PAGE-FORGOTUI-004: submitting delegates to the hook', () => {
setForgot({ email: 'a@b.de' })
render(<ForgotPasswordPage />)
fireEvent.submit(screen.getByRole('button', { name: 'Send reset link' }).closest('form') as HTMLFormElement)
expect(handleSubmit).toHaveBeenCalled()
})
it('FE-PAGE-FORGOTUI-005: a running submit disables the button and shows the pending label', () => {
setForgot({ isLoading: true })
render(<ForgotPasswordPage />)
const btn = screen.getByRole('button', { name: 'Signing in…' })
expect(btn).toBeDisabled()
expect(btn.style.opacity).toBe('0.7')
expect(btn.style.cursor).toBe('default')
})
it('FE-PAGE-FORGOTUI-006: the SMTP hint appears on the form only when the probe said no', () => {
setForgot({ smtpConfigured: false })
const { rerender } = render(<ForgotPasswordPage />)
expect(screen.getByText(/console/i)).toBeInTheDocument()
// Still pending (null) or configured (true) keeps the hint hidden.
setForgot({ smtpConfigured: null })
rerender(<ForgotPasswordPage />)
expect(screen.queryByText(/console/i)).toBeNull()
setForgot({ smtpConfigured: true })
rerender(<ForgotPasswordPage />)
expect(screen.queryByText(/console/i)).toBeNull()
})
it('FE-PAGE-FORGOTUI-007: after submitting, the confirmation replaces the form', () => {
setForgot({ submitted: true })
render(<ForgotPasswordPage />)
expect(screen.getByRole('heading', { name: 'Check your email' })).toBeInTheDocument()
expect(screen.queryByPlaceholderText('your@email.com')).toBeNull()
expect(screen.queryByText(/console/i)).toBeNull()
// Both the top link and the bottom button navigate back to the login page.
const backButtons = screen.getAllByRole('button', { name: 'Back to sign in' })
expect(backButtons).toHaveLength(2)
fireEvent.click(backButtons[1])
expect(navigate).toHaveBeenCalledWith('/login')
})
it('FE-PAGE-FORGOTUI-008: the confirmation repeats the SMTP warning when mail is not configured', () => {
setForgot({ submitted: true, smtpConfigured: false })
render(<ForgotPasswordPage />)
expect(screen.getByRole('heading', { name: 'Check your email' })).toBeInTheDocument()
expect(screen.getByText(/console/i)).toBeInTheDocument()
})
})
+277
View File
@@ -0,0 +1,277 @@
import React from 'react'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { render, screen, fireEvent } from '../../tests/helpers/render'
import type { HelpNavSection, HelpPageData } from '../api/client'
import HelpPage from './HelpPage'
// FE-PAGE-HELPUI-001 to FE-PAGE-HELPUI-014
//
// HelpPage is a wiring container over useHelp (covered in help/useHelp.test.ts):
// the hook is mocked here so every render branch — loading, error, markdown,
// search, mobile drawer — can be driven directly.
type HelpState = ReturnType<typeof buildHelp>
const mocks = vi.hoisted(() => ({ help: {} as Record<string, unknown> }))
vi.mock('./help/useHelp', () => ({ useHelp: () => mocks.help }))
vi.mock('../components/Layout/Navbar', () => ({
default: () => React.createElement('nav', { 'data-testid': 'navbar' }),
}))
const setQuery = vi.fn((_v: string) => {})
const setNavOpen = vi.fn((_v: boolean) => {})
const SECTIONS: HelpNavSection[] = [
{ title: 'Getting started', pages: [{ slug: 'Home', title: 'Home' }, { slug: 'Install', title: 'Install' }] },
{ title: '', pages: [{ slug: 'FAQ', title: 'FAQ' }] },
]
function buildHelp(over: Record<string, unknown> = {}) {
return {
page: null as HelpPageData | null,
loading: false,
pageError: false,
query: '',
setQuery,
navOpen: false,
setNavOpen,
contentRef: { current: null } as React.RefObject<HTMLDivElement | null>,
activeSlug: 'Home',
filtered: SECTIONS,
...over,
}
}
function setHelp(over: Record<string, unknown> = {}) {
mocks.help = buildHelp(over) as unknown as Record<string, unknown>
return mocks.help as unknown as HelpState
}
function page(markdown: string): HelpPageData {
return { slug: 'Home', title: 'Home', markdown }
}
beforeEach(() => {
setQuery.mockClear()
setNavOpen.mockClear()
setHelp()
})
describe('HelpPage', () => {
it('FE-PAGE-HELPUI-001: renders the desktop sidebar with section titles and page links', () => {
setHelp()
render(<HelpPage />)
expect(screen.getByText('Help & Docs')).toBeInTheDocument()
expect(screen.getByText('Getting started')).toBeInTheDocument()
// The section with an empty title renders no heading, only its pages.
expect(screen.getByRole('link', { name: 'FAQ' })).toHaveAttribute('href', '/help/FAQ')
expect(screen.getByRole('link', { name: 'Install' })).toHaveAttribute('href', '/help/Install')
})
it('FE-PAGE-HELPUI-002: marks the active page and indents the inactive ones', () => {
setHelp({ activeSlug: 'Install' })
render(<HelpPage />)
const active = screen.getByRole('link', { name: 'Install' })
expect(active.className).toContain('text-accent')
expect(active.querySelector('span')?.className).toBe('')
const inactive = screen.getByRole('link', { name: 'FAQ' })
expect(inactive.className).toContain('text-content-secondary')
expect(inactive.querySelector('span')?.className).toContain('pl-[18px]')
})
it('FE-PAGE-HELPUI-003: typing in the search box reports the query upwards', () => {
setHelp({ query: 'ins' })
render(<HelpPage />)
const input = screen.getByPlaceholderText('Search docs…')
expect(input).toHaveValue('ins')
fireEvent.change(input, { target: { value: 'inst' } })
expect(setQuery).toHaveBeenCalledWith('inst')
})
it('FE-PAGE-HELPUI-004: an empty result set shows the no-results hint instead of links', () => {
setHelp({ filtered: [], query: 'zzz' })
render(<HelpPage />)
expect(screen.getByText('No matching pages.')).toBeInTheDocument()
expect(screen.queryByRole('link')).toBeNull()
})
it('FE-PAGE-HELPUI-005: shows a spinner while the page loads', () => {
setHelp({ loading: true, page: page('# Ignored') })
render(<HelpPage />)
expect(document.querySelector('.animate-spin')).toBeInTheDocument()
expect(screen.queryByRole('heading', { name: 'Ignored' })).toBeNull()
})
it('FE-PAGE-HELPUI-006: a failed fetch shows the error block, not the stale page', () => {
setHelp({ pageError: true, page: page('# Stale') })
render(<HelpPage />)
expect(screen.getByText("Couldn't load this page")).toBeInTheDocument()
expect(screen.getByText(/fetched from the TREK wiki/)).toBeInTheDocument()
expect(screen.queryByRole('heading', { name: 'Stale' })).toBeNull()
})
it('FE-PAGE-HELPUI-007: renders nothing in the content area when no page is loaded', () => {
setHelp({ page: null })
render(<HelpPage />)
expect(document.querySelector('article.wiki-prose')).toBeNull()
expect(document.querySelector('.animate-spin')).toBeNull()
})
it('FE-PAGE-HELPUI-008: the mobile drawer opens from the contents button', () => {
setHelp()
render(<HelpPage />)
expect(screen.getAllByText('Help & Docs')).toHaveLength(1)
fireEvent.click(screen.getByRole('button', { name: 'Contents' }))
expect(setNavOpen).toHaveBeenCalledWith(true)
})
it('FE-PAGE-HELPUI-009: the open drawer closes on the backdrop and on its close button, but not on itself', () => {
setHelp({ navOpen: true })
render(<HelpPage />)
// Nav is rendered twice while the drawer is open (sidebar + drawer).
expect(screen.getAllByText('Help & Docs')).toHaveLength(2)
expect(screen.getAllByRole('link', { name: 'FAQ' })).toHaveLength(2)
const drawer = document.querySelector('.fixed.inset-0.z-\\[120\\]') as HTMLElement
const panel = drawer.querySelector('.shadow-xl') as HTMLElement
fireEvent.click(panel)
expect(setNavOpen).not.toHaveBeenCalled()
// The X button sits in the drawer header, before the nav.
const closeBtn = panel.querySelector('button') as HTMLButtonElement
fireEvent.click(closeBtn)
expect(setNavOpen).toHaveBeenCalledWith(false)
setNavOpen.mockClear()
fireEvent.click(drawer)
expect(setNavOpen).toHaveBeenCalledWith(false)
})
it('FE-PAGE-HELPUI-010: renders headings with GitHub-compatible anchor ids', () => {
setHelp({
page: page(
['# Getting Started!', '', '## Trips & Days', '', '### Sub Heading', '', '#### Deep Heading'].join('\n'),
),
})
render(<HelpPage />)
expect(screen.getByRole('heading', { level: 1 }).id).toBe('getting-started')
// "&" is punctuation and drops out; the surrounding spaces collapse into one hyphen.
expect(screen.getByRole('heading', { level: 2 }).id).toBe('trips-days')
// The sidebar section titles are h3s too, so match this one by its text.
expect(screen.getByRole('heading', { name: 'Sub Heading' }).id).toBe('sub-heading')
expect(screen.getByRole('heading', { level: 4 }).id).toBe('deep-heading')
})
it('FE-PAGE-HELPUI-011: a heading built from inline markup drops the non-text children from its id', () => {
setHelp({ page: page('## Trip **Planner** 2') })
render(<HelpPage />)
// "Planner" arrives as a <strong> element, so only the plain-text parts feed the slug.
expect(screen.getByRole('heading', { level: 2 }).id).toBe('trip-2')
expect(screen.getByText('Planner').tagName).toBe('STRONG')
})
it('FE-PAGE-HELPUI-012: routes internal links through the SPA router and opens external ones in a tab', () => {
setHelp({
page: page(
[
'[jump](#trips)',
'',
'[planner](/trips/1)',
'',
'[github](https://github.com/liketrek/TREK)',
].join('\n'),
),
})
render(<HelpPage />)
const anchor = screen.getByRole('link', { name: 'jump' })
expect(anchor).toHaveAttribute('href', '#trips')
expect(anchor).not.toHaveAttribute('target')
// An internal link becomes a router <Link> — still an <a href>, but without target.
expect(screen.getByRole('link', { name: 'planner' })).toHaveAttribute('href', '/trips/1')
const external = screen.getByRole('link', { name: 'github' })
expect(external).toHaveAttribute('target', '_blank')
expect(external).toHaveAttribute('rel', 'noopener noreferrer')
})
it('FE-PAGE-HELPUI-013: styles lists, quotes, images, rules and both code flavours', () => {
setHelp({
page: page(
[
'Intro text.',
'',
'- first',
'- second',
'',
'1. one',
'2. two',
'',
'> quoted line',
'',
'![screenshot](/img/a.png)',
'',
'Use `npm run dev` to start.',
'',
'```bash',
'npm test',
'```',
'',
'---',
].join('\n'),
),
})
render(<HelpPage />)
expect(screen.getByText('Intro text.').tagName).toBe('P')
expect(document.querySelector('ul.list-disc')).toBeInTheDocument()
expect(document.querySelector('ol.list-decimal')).toBeInTheDocument()
expect(screen.getByText('first').tagName).toBe('LI')
expect(screen.getByText('quoted line').closest('blockquote')).toBeInTheDocument()
expect(document.querySelector('hr')).toBeInTheDocument()
const img = screen.getByRole('img', { name: 'screenshot' })
expect(img.getAttribute('src')).toBe('/img/a.png')
expect(img).toHaveAttribute('loading', 'lazy')
// Inline code keeps the pill styling; a fenced block keeps its language class.
expect(screen.getByText('npm run dev').className).toContain('bg-surface-tertiary')
const block = screen.getByText('npm test')
expect(block.className).toContain('language-bash')
expect(block.closest('pre')?.className).toContain('overflow-x-auto')
})
it('FE-PAGE-HELPUI-014: renders GFM tables inside a horizontally scrollable wrapper', () => {
setHelp({
page: page(['| Key | Meaning |', '| --- | --- |', '| esc | close |'].join('\n')),
})
render(<HelpPage />)
expect(screen.getByRole('columnheader', { name: 'Key' })).toBeInTheDocument()
expect(screen.getByRole('cell', { name: 'close' })).toBeInTheDocument()
expect(screen.getByRole('table').parentElement?.className).toContain('overflow-x-auto')
})
it('FE-PAGE-HELPUI-015: an image without a target still renders with its alt text', () => {
setHelp({ page: page('![alt only]()') })
render(<HelpPage />)
const img = screen.getByRole('img', { name: 'alt only' })
expect(img.className).toContain('border-edge')
expect(img.getAttribute('src')).toBeFalsy()
})
})
@@ -0,0 +1,461 @@
// FE-JRN-DETWIRE-001 to FE-JRN-DETWIRE-028
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, fireEvent, waitFor, within } from '../../tests/helpers/render';
import { journeyApi } from '../api/client';
import { useAuthStore } from '../store/authStore';
import { useJourneyStore } from '../store/journeyStore';
import type { JourneyDetail, JourneyEntry } from '../store/journeyStore';
import JourneyDetailPage from './JourneyDetailPage';
const mocks = vi.hoisted(() => ({
detail: {} as Record<string, unknown>,
captured: {} as Record<string, Record<string, unknown>>,
downloadPdf: vi.fn(),
}));
vi.mock('./journeyDetail/useJourneyDetail', () => ({
useJourneyDetail: () => mocks.detail,
}));
vi.mock('../components/Layout/Navbar', () => ({ default: () => <nav data-testid="navbar" /> }));
vi.mock('../mobile/screens/journey/MJourneyDetail', () => ({
default: () => <div data-testid="mobile-detail" />,
}));
vi.mock('../components/PDF/JourneyBookPDF', () => ({
downloadJourneyBookPDF: mocks.downloadPdf,
}));
vi.mock('../components/Journey/JourneyMapAuto', async () => {
const React = await import('react');
const Comp = React.forwardRef((props: Record<string, unknown>, ref: React.Ref<unknown>) => {
React.useImperativeHandle(ref, () => ({ highlightMarker: vi.fn(), focusMarker: vi.fn(), invalidateSize: vi.fn() }));
mocks.captured.map = props;
return <div data-testid="sidebar-map" data-active={String(props.activeMarkerId ?? '')} />;
});
Comp.displayName = 'MockJourneyMapAuto';
return { __esModule: true, default: Comp };
});
function capture(name: string, testId: string) {
return (props: Record<string, unknown>) => {
mocks.captured[name] = props;
return <div data-testid={testId} />;
};
}
vi.mock('../components/Journey/MobileMapTimeline', () => ({ default: capture('mobileTimeline', 'mobile-timeline') }));
vi.mock('../components/Journey/MobileEntryView', () => ({ default: capture('mobileEntry', 'mobile-entry') }));
vi.mock('../components/Journey/PhotoLightbox', () => ({ default: capture('lightbox', 'lightbox') }));
vi.mock('../components/Journey/ContributorInviteDialog', () => ({ default: capture('invite', 'invite-dialog') }));
vi.mock('../components/Journey/JourneyDetailPageGalleryView', () => ({ GalleryView: capture('gallery', 'gallery-view') }));
vi.mock('../components/Journey/JourneyDetailPageEntryEditor', () => ({ EntryEditor: capture('editor', 'entry-editor') }));
vi.mock('../components/Journey/JourneyDetailPageAddTripDialog', () => ({ AddTripDialog: capture('addTrip', 'add-trip-dialog') }));
vi.mock('../components/Journey/JourneyDetailPageSettingsDialog', () => ({ JourneySettingsDialog: capture('settings', 'settings-dialog') }));
vi.mock('../components/Journey/JourneyDetailPageEntryCard', () => ({
EntryCard: capture('entryCard', 'entry-card'),
SkeletonCard: capture('skeletonCard', 'skeleton-card'),
CheckinCard: capture('checkinCard', 'checkin-card'),
}));
// ── Fixtures ─────────────────────────────────────────────────────────────────
function buildEntry(over: Partial<JourneyEntry> = {}): JourneyEntry {
return {
id: 1, journey_id: 7, author_id: 1, type: 'entry', title: 'Arrival', story: null,
entry_date: '2026-05-01', entry_time: null, location_name: 'Tokyo',
location_lat: 35.6, location_lng: 139.7, mood: null, weather: null,
tags: [], pros_cons: null, visibility: 'private', sort_order: 0, photos: [],
created_at: 0, updated_at: 0,
...over,
};
}
function buildDetail(over: Partial<JourneyDetail> = {}): JourneyDetail {
return {
id: 7, user_id: 1, title: 'Japan 2026', subtitle: 'Tokyo & Kyoto',
cover_gradient: null, cover_image: null, status: 'active', created_at: 0, updated_at: 0,
entries: [buildEntry(), buildEntry({ id: 2, title: 'Second stop' })],
gallery: [], trips: [], contributors: [{ journey_id: 7, user_id: 5, role: 'owner', added_at: 0, username: 'maurice', avatar: null }],
stats: { entries: 2, photos: 3, places: 4 },
...over,
};
}
const toast = { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() };
function buildHook(over: Record<string, unknown> = {}): Record<string, unknown> {
const current = 'current' in over ? (over.current as JourneyDetail | null) : buildDetail();
return {
id: '7', navigate: vi.fn(), toast, t: (key: string) => key, locale: 'en',
current, loading: false,
canEditEntries: true, canEditJourney: true, myRole: 'owner',
view: 'timeline', setView: vi.fn(), activeEntryId: null, setActiveEntryId: vi.fn(),
feedRef: { current: null },
viewingEntry: null, setViewingEntry: vi.fn(),
editingEntry: null, setEditingEntry: vi.fn(),
lightbox: null, setLightbox: vi.fn(),
deleteTarget: null, setDeleteTarget: vi.fn(),
showInvite: false, setShowInvite: vi.fn(),
showAddTrip: false, setShowAddTrip: vi.fn(),
unlinkTrip: null, setUnlinkTrip: vi.fn(),
showSettings: false, setShowSettings: vi.fn(),
hideSkeletons: false, setHideSkeletons: vi.fn(),
mapRef: { current: null }, fullMapRef: { current: null },
activeLocationId: null, handleMarkerClick: vi.fn(), handleLocationClick: vi.fn(),
mapEntries: [], sidebarMapItems: [], tripDates: new Set<string>(), isMobile: false,
loadJourney: vi.fn(), updateEntry: vi.fn(async () => {}), deleteEntry: vi.fn(async () => {}),
reorderEntries: vi.fn(async () => {}), uploadPhotos: vi.fn(async () => ({ succeeded: [], failed: [] })),
deletePhoto: vi.fn(async () => {}),
...over,
};
}
function setup(over: Record<string, unknown> = {}) {
mocks.detail = buildHook(over);
const view = render(<JourneyDetailPage />);
return { ...view, hook: mocks.detail };
}
const journeyStoreInitial = useJourneyStore.getState();
let createEntry: ReturnType<typeof vi.fn>;
beforeEach(() => {
vi.clearAllMocks();
mocks.captured = {};
createEntry = vi.fn(async () => buildEntry({ id: 88 }));
useJourneyStore.setState({ ...journeyStoreInitial, createEntry } as never, true);
useAuthStore.setState({ user: { id: 5, username: 'maurice' } } as never);
});
// ── Tests ────────────────────────────────────────────────────────────────────
describe('JourneyDetailPage wiring', () => {
it('FE-JRN-DETWIRE-001: shows the spinner while the journey loads', () => {
setup({ loading: true, current: null });
expect(screen.getByTestId('navbar')).toBeInTheDocument();
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
});
it('FE-JRN-DETWIRE-002: renders the hero with the journey stats and the sidebar map', () => {
setup();
expect(screen.getByRole('heading', { name: 'Japan 2026' })).toBeInTheDocument();
expect(screen.getByText('Tokyo & Kyoto')).toBeInTheDocument();
expect(screen.getByTestId('sidebar-map')).toBeInTheDocument();
// days / places / entries / photos
expect(screen.getByText('3')).toBeInTheDocument();
expect(screen.getByText('4')).toBeInTheDocument();
});
it('FE-JRN-DETWIRE-003: the hero back button returns to the journey list', () => {
const { hook } = setup();
fireEvent.click(screen.getByRole('button', { name: 'journey.detail.backToJourney' }));
expect(hook.navigate).toHaveBeenCalledWith('/journey');
});
it('FE-JRN-DETWIRE-004: the download button lazy-loads the PDF book renderer', async () => {
const { hook } = setup();
const buttons = screen.getAllByRole('button');
fireEvent.click(buttons[1]);
await waitFor(() => expect(mocks.downloadPdf).toHaveBeenCalledWith(hook.current));
});
it('FE-JRN-DETWIRE-005: the eye toggle flips hide_skeletons and persists the preference', async () => {
const update = vi.spyOn(journeyApi, 'updatePreferences').mockResolvedValue({});
const { hook } = setup();
fireEvent.click(screen.getByText('journey.skeletons.hide').closest('div')!.querySelector('button')!);
expect(hook.setHideSkeletons).toHaveBeenCalledWith(true);
await waitFor(() => expect(update).toHaveBeenCalledWith(7, { hide_skeletons: true }));
});
it('FE-JRN-DETWIRE-006: with skeletons hidden the toggle offers to show them again', () => {
setup({ hideSkeletons: true });
expect(screen.getByText('journey.skeletons.show')).toBeInTheDocument();
});
it('FE-JRN-DETWIRE-007: the timeline groups entries per day and renders one card each', () => {
setup({
current: buildDetail({
entries: [
buildEntry({ id: 1 }),
buildEntry({ id: 2, title: 'Second stop' }),
buildEntry({ id: 3, title: 'Day two', entry_date: '2026-05-02' }),
],
}),
});
expect(screen.getAllByTestId('entry-card')).toHaveLength(3);
// one day header per distinct entry_date
expect(screen.getAllByRole('heading', { level: 3 })).toHaveLength(2);
});
it('FE-JRN-DETWIRE-008: an empty timeline shows the mascot empty state', () => {
setup({ current: buildDetail({ entries: [] }) });
expect(screen.getByText('journey.detail.noEntries')).toBeInTheDocument();
expect(screen.queryByTestId('entry-card')).not.toBeInTheDocument();
});
it('FE-JRN-DETWIRE-009: skeleton and check-in entries get their own cards', () => {
setup({
current: buildDetail({
entries: [
buildEntry({ id: 1, type: 'skeleton', title: 'Suggested' }),
buildEntry({ id: 2, type: 'checkin', title: 'Checked in' }),
],
}),
});
expect(screen.getByTestId('skeleton-card')).toBeInTheDocument();
expect(screen.getByTestId('checkin-card')).toBeInTheDocument();
(mocks.captured.skeletonCard.onClick as () => void)();
(mocks.captured.checkinCard.onClick as () => void)();
expect(mocks.detail.setEditingEntry).toHaveBeenCalledTimes(2);
});
it('FE-JRN-DETWIRE-010: a read-only viewer cannot open the skeleton or check-in cards', () => {
setup({
canEditEntries: false,
current: buildDetail({
entries: [
buildEntry({ id: 1, type: 'skeleton', title: 'Suggested' }),
buildEntry({ id: 2, type: 'checkin', title: 'Checked in' }),
],
}),
});
expect(mocks.captured.skeletonCard.onClick).toBeUndefined();
expect(mocks.captured.checkinCard.onClick).toBeUndefined();
expect(screen.queryByText('journey.detail.addEntry')).not.toBeInTheDocument();
});
it('FE-JRN-DETWIRE-011: the reorder arrows move an entry within its day', async () => {
const { hook } = setup();
const down = screen.getAllByRole('button', { name: 'Move down' })[0];
const upFirst = screen.getAllByRole('button', { name: 'Move up' })[0];
expect(upFirst).toBeDisabled();
fireEvent.click(down);
await waitFor(() => expect(hook.reorderEntries).toHaveBeenCalledWith(7, [2, 1]));
fireEvent.click(screen.getAllByRole('button', { name: 'Move up' })[1]);
expect(hook.reorderEntries).toHaveBeenLastCalledWith(7, [2, 1]);
});
it('FE-JRN-DETWIRE-012: a failing reorder is reported to the user', async () => {
const reorderEntries = vi.fn(async () => { throw new Error('conflict'); });
setup({ reorderEntries });
fireEvent.click(screen.getAllByRole('button', { name: 'Move down' })[0]);
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('common.errorOccurred'));
});
it('FE-JRN-DETWIRE-013: entry-card actions open the editor, the delete confirm and the lightbox', () => {
const { hook } = setup();
const card = mocks.captured.entryCard;
(card.onEdit as () => void)();
expect(hook.setEditingEntry).toHaveBeenCalled();
(card.onDelete as () => void)();
expect(hook.setDeleteTarget).toHaveBeenCalled();
const onPhotoClick = card.onPhotoClick as (p: Record<string, unknown>[], i: number) => void;
onPhotoClick([{ id: 3, photo_id: 30, caption: 'x', media_type: 'image' }], 0);
expect(hook.setLightbox).toHaveBeenCalledWith({
index: 0,
photos: [expect.objectContaining({ id: 3, src: '/api/photos/30/original', caption: 'x' })],
});
});
it('FE-JRN-DETWIRE-014: the add-entry button opens a draft, the gallery tab an upload', () => {
const { hook, unmount } = setup();
fireEvent.click(screen.getByText('journey.detail.addEntry'));
expect(hook.setEditingEntry).toHaveBeenCalledWith(expect.objectContaining({ id: 0, journey_id: 7 }));
const upload = vi.fn();
(mocks.captured.gallery.onRegisterUpload as (fn: () => void) => void)(upload);
unmount();
setup({ view: 'gallery' });
(mocks.captured.gallery.onRegisterUpload as (fn: () => void) => void)(upload);
fireEvent.click(screen.getByText('common.upload'));
expect(upload).toHaveBeenCalledTimes(1);
});
it('FE-JRN-DETWIRE-015: the view switcher and gallery photo clicks feed back into the hook', () => {
const { hook } = setup();
fireEvent.click(screen.getByRole('button', { name: /journey.share.gallery/ }));
expect(hook.setView).toHaveBeenCalledWith('gallery');
const onPhotoClick = mocks.captured.gallery.onPhotoClick as (p: Record<string, unknown>[], i: number) => void;
onPhotoClick([{ id: 9, photo_id: 90, media_type: 'video' }], 0);
expect(hook.setLightbox).toHaveBeenCalledWith({
index: 0,
photos: [expect.objectContaining({ id: 9, src: '/api/photos/90/original', caption: null, mediaType: 'video' })],
});
(mocks.captured.gallery.onRefresh as () => void)();
expect(hook.loadJourney).toHaveBeenCalledWith(7);
});
it('FE-JRN-DETWIRE-016: the entry editor creates a new entry and updates an existing one', async () => {
const { hook, unmount } = setup({ editingEntry: buildEntry({ id: 0 }) });
const save = mocks.captured.editor.onSave as (d: Record<string, unknown>, id?: number) => Promise<number>;
await expect(save({ title: 'Fresh' })).resolves.toBe(88);
expect(createEntry).toHaveBeenCalledWith(7, { title: 'Fresh' });
await (mocks.captured.editor.onUploadPhotos as (id: number, f: File[]) => Promise<unknown>)(88, []);
expect(hook.uploadPhotos).toHaveBeenCalledWith(88, [], undefined);
const addProvider = vi.spyOn(journeyApi, 'addProviderPhotos').mockResolvedValue({ added: 1 });
await (mocks.captured.editor.onAddProviderPhotos as (id: number, g: Record<string, unknown>) => Promise<void>)(
88, { provider: 'immich', assetIds: ['a1'], passphrase: 'pw', mediaTypes: ['image'] },
);
expect(addProvider).toHaveBeenCalledWith(88, 'immich', ['a1'], undefined, 'pw', ['image']);
(mocks.captured.editor.onDone as () => void)();
expect(hook.setEditingEntry).toHaveBeenCalledWith(null);
expect(hook.loadJourney).toHaveBeenCalledWith(7);
unmount();
const second = setup({ editingEntry: buildEntry({ id: 4 }) });
const save2 = mocks.captured.editor.onSave as (d: Record<string, unknown>, id?: number) => Promise<number>;
await expect(save2({ title: 'Edited' }, 4)).resolves.toBe(4);
expect(second.hook.updateEntry).toHaveBeenCalledWith(4, { title: 'Edited' });
});
it('FE-JRN-DETWIRE-017: settings, add-trip and invite dialogs report back into the hook', () => {
const trips = [
{ trip_id: 3, added_at: 0, title: 'Tokyo', start_date: '2026-05-01', end_date: '2026-05-04', cover_image: null, currency: 'EUR', place_count: 2 },
];
const { hook } = setup({
current: buildDetail({ trips }),
showSettings: true, showAddTrip: true, showInvite: true,
});
(mocks.captured.settings.onSaved as () => void)();
expect(hook.setShowSettings).toHaveBeenCalledWith(false);
(mocks.captured.settings.onOpenInvite as () => void)();
expect(hook.setShowInvite).toHaveBeenCalledWith(true);
(mocks.captured.settings.onRefresh as () => void)();
(mocks.captured.settings.onClose as () => void)();
expect(mocks.captured.addTrip.existingTripIds).toEqual([3]);
(mocks.captured.addTrip.onAdded as () => void)();
expect(hook.setShowAddTrip).toHaveBeenCalledWith(false);
(mocks.captured.addTrip.onClose as () => void)();
expect(mocks.captured.invite.existingUserIds).toEqual([5]);
(mocks.captured.invite.onInvited as () => void)();
expect(hook.setShowInvite).toHaveBeenCalledWith(false);
(mocks.captured.invite.onClose as () => void)();
expect(hook.loadJourney).toHaveBeenCalledWith(7);
});
it('FE-JRN-DETWIRE-018: confirming the entry delete removes it and reloads', async () => {
const target = buildEntry({ id: 4, title: 'Old' });
const { hook } = setup({ deleteTarget: target });
const heading = screen.getByRole('heading', { name: 'journey.entries.deleteTitle' });
const dialog = heading.closest('.trek-modal-enter') as HTMLElement;
fireEvent.click(within(dialog).getByRole('button', { name: 'common.delete' }));
await waitFor(() => expect(hook.deleteEntry).toHaveBeenCalledWith(4));
expect(hook.setDeleteTarget).toHaveBeenCalledWith(null);
expect(hook.loadJourney).toHaveBeenCalledWith(7);
});
it('FE-JRN-DETWIRE-019: confirming the trip unlink calls the API and refreshes', async () => {
const removeTrip = vi.spyOn(journeyApi, 'removeTrip').mockResolvedValue({});
const { hook } = setup({ unlinkTrip: { trip_id: 3, title: 'Tokyo trip' } });
fireEvent.click(screen.getByRole('button', { name: 'journey.trips.unlink' }));
await waitFor(() => expect(removeTrip).toHaveBeenCalledWith(7, 3));
expect(toast.success).toHaveBeenCalledWith('journey.trips.tripUnlinked');
expect(hook.setUnlinkTrip).toHaveBeenCalledWith(null);
});
it('FE-JRN-DETWIRE-020: a failing unlink shows an error instead', async () => {
vi.spyOn(journeyApi, 'removeTrip').mockRejectedValue(new Error('boom'));
setup({ unlinkTrip: { trip_id: 3, title: 'Tokyo trip' } });
fireEvent.click(screen.getByRole('button', { name: 'journey.trips.unlink' }));
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('journey.trips.unlinkFailed'));
});
it('FE-JRN-DETWIRE-021: the lightbox is rendered from the hook state and closes back into it', () => {
const { hook } = setup({
lightbox: { photos: [{ id: 3, src: '/api/photos/30/original', caption: null }], index: 0 },
});
expect(screen.getByTestId('lightbox')).toBeInTheDocument();
expect(mocks.captured.lightbox.photos).toEqual([expect.objectContaining({ id: '3' })]);
(mocks.captured.lightbox.onClose as () => void)();
expect(hook.setLightbox).toHaveBeenCalledWith(null);
});
it('FE-JRN-DETWIRE-022: on mobile the combined map timeline replaces the desktop panes', () => {
const { hook } = setup({ isMobile: true });
expect(screen.getByTestId('mobile-timeline')).toBeInTheDocument();
expect(screen.queryByTestId('sidebar-map')).not.toBeInTheDocument();
(mocks.captured.mobileTimeline.onEntryClick as (e: JourneyEntry) => void)(buildEntry({ id: 2 }));
expect(hook.setViewingEntry).toHaveBeenCalledWith(expect.objectContaining({ id: 2 }));
(mocks.captured.mobileTimeline.onAddEntry as () => void)();
expect(hook.setEditingEntry).toHaveBeenCalledWith(expect.objectContaining({ id: 0 }));
});
it('FE-JRN-DETWIRE-023: a read-only mobile viewer gets no add-entry affordance', () => {
setup({ isMobile: true, canEditEntries: false });
expect(mocks.captured.mobileTimeline.onAddEntry).toBeUndefined();
expect(mocks.captured.mobileTimeline.readOnly).toBe(true);
});
it('FE-JRN-DETWIRE-024: the floating mobile bar switches views, goes back and opens settings', () => {
const { hook } = setup({ isMobile: true });
// The hero keeps its own back button in the DOM (hidden via class) — the
// floating bar is the first one.
fireEvent.click(screen.getAllByRole('button', { name: 'journey.detail.backToJourney' })[0]);
expect(hook.navigate).toHaveBeenCalledWith('/journey');
fireEvent.click(screen.getAllByRole('button', { name: /journey.share.gallery/ })[0]);
expect(hook.setView).toHaveBeenCalledWith('gallery');
fireEvent.click(screen.getAllByRole('button', { name: /journey.detail.journeyTab/ })[0]);
expect(hook.setView).toHaveBeenCalledWith('timeline');
fireEvent.click(screen.getByRole('button', { name: 'journey.settings.title' }));
expect(hook.setShowSettings).toHaveBeenCalledWith(true);
});
it('FE-JRN-DETWIRE-025: a non-owner sees a spacer instead of the mobile settings button', () => {
setup({ isMobile: true, canEditJourney: false });
expect(screen.queryByRole('button', { name: 'journey.settings.title' })).not.toBeInTheDocument();
});
it('FE-JRN-DETWIRE-026: the fullscreen mobile entry view wires edit, delete and photos', () => {
const viewingEntry = buildEntry({ id: 6, title: 'Viewed' });
const { hook } = setup({ isMobile: true, viewingEntry });
expect(screen.getByTestId('mobile-entry')).toBeInTheDocument();
(mocks.captured.mobileEntry.onEdit as () => void)();
expect(hook.setViewingEntry).toHaveBeenCalledWith(null);
expect(hook.setEditingEntry).toHaveBeenCalledWith(viewingEntry);
(mocks.captured.mobileEntry.onDelete as () => void)();
expect(hook.setDeleteTarget).toHaveBeenCalledWith(viewingEntry);
(mocks.captured.mobileEntry.onClose as () => void)();
expect(hook.setViewingEntry).toHaveBeenCalledWith(null);
const onPhotoClick = mocks.captured.mobileEntry.onPhotoClick as (p: Record<string, unknown>[], i: number) => void;
onPhotoClick([{ id: 7, photo_id: 70, caption: 'c', media_type: 'image' }], 0);
expect(hook.setLightbox).toHaveBeenCalledWith({
index: 0,
photos: [expect.objectContaining({ id: 7, src: '/api/photos/70/original' })],
});
});
it('FE-JRN-DETWIRE-027: an archived journey shows its status badge', () => {
setup({ current: buildDetail({ status: 'archived' }) });
expect(screen.getByText('journey.status.archived')).toBeInTheDocument();
});
it('FE-JRN-DETWIRE-028: a cover image is layered behind the hero gradient', () => {
setup({ current: buildDetail({ cover_image: 'covers/j.jpg' }) });
expect(document.querySelector('img[src="/uploads/covers/j.jpg"]')).toBeInTheDocument();
});
});
@@ -0,0 +1,208 @@
// FE-JRN-LISTWIRE-001 to FE-JRN-LISTWIRE-014
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, fireEvent } from '../../tests/helpers/render';
import type { Journey } from '../store/journeyStore';
import JourneyPage from './JourneyPage';
const mocks = vi.hoisted(() => ({ journey: {} as Record<string, unknown> }));
vi.mock('./journey/useJourney', () => ({ useJourney: () => mocks.journey }));
vi.mock('../components/Layout/Navbar', () => ({ default: () => <nav data-testid="navbar" /> }));
vi.mock('../mobile/screens/journey/MJourney', () => ({ default: () => <div data-testid="mobile-journey" /> }));
type ListItem = Journey & {
entry_count?: number;
photo_count?: number;
place_count?: number;
trip_date_min?: string | null;
trip_date_max?: string | null;
};
function buildJourney(over: Partial<ListItem> = {}): ListItem {
return {
id: 1, user_id: 1, title: 'Japan 2026', subtitle: null,
cover_gradient: null, cover_image: null, status: 'completed',
created_at: new Date('2026-02-01T00:00:00Z').getTime(), updated_at: 0,
...over,
};
}
function buildHook(over: Record<string, unknown> = {}): Record<string, unknown> {
const journeys = (over.journeys as ListItem[]) ?? [];
return {
navigate: vi.fn(), journeys, loading: false,
showCreate: false, setShowCreate: vi.fn(),
newTitle: '', setNewTitle: vi.fn(),
newSubtitle: '', setNewSubtitle: vi.fn(),
availableTrips: [], selectedTripIds: new Set<number>(), setSelectedTripIds: vi.fn(),
searchOpen: false, setSearchOpen: vi.fn(), searchQuery: '', setSearchQuery: vi.fn(),
searchInputRef: { current: null },
activeSuggestion: undefined, setDismissedSuggestions: vi.fn(),
activeJourney: null, activeJourneyIsLive: false,
filteredJourneys: journeys,
openCreateModal: vi.fn(), handleCreate: vi.fn(), totalPlaces: 0,
...over,
};
}
function setup(over: Record<string, unknown> = {}) {
mocks.journey = buildHook(over);
const view = render(<JourneyPage />);
return { ...view, hook: mocks.journey };
}
beforeEach(() => {
vi.clearAllMocks();
});
describe('JourneyPage wiring', () => {
it('FE-JRN-LISTWIRE-001: renders the section header and the create card', () => {
setup();
expect(screen.getByText('All Journeys')).toBeInTheDocument();
expect(screen.getByText('Create a new Journey')).toBeInTheDocument();
});
it('FE-JRN-LISTWIRE-002: the mobile search button opens the field and focuses it', () => {
const input = document.createElement('input');
const focus = vi.spyOn(input, 'focus');
vi.useFakeTimers();
try {
const { hook, container } = setup({ searchInputRef: { current: input } });
fireEvent.click(container.querySelectorAll('button')[0]);
expect(hook.setSearchOpen).toHaveBeenCalledWith(true);
vi.advanceTimersByTime(100);
expect(focus).toHaveBeenCalled();
} finally {
vi.useRealTimers();
}
});
it('FE-JRN-LISTWIRE-003: pressing the search button again closes it and clears the query', () => {
const { hook, container } = setup({ searchOpen: true, searchQuery: 'kyoto' });
fireEvent.click(container.querySelectorAll('button')[0]);
expect(hook.setSearchOpen).toHaveBeenCalledWith(false);
expect(hook.setSearchQuery).toHaveBeenCalledWith('');
});
it('FE-JRN-LISTWIRE-004: typing filters and Escape resets the search box', () => {
const { hook } = setup({ searchOpen: true, searchQuery: '' });
const box = screen.getByPlaceholderText('Search journeys…');
fireEvent.change(box, { target: { value: 'kyo' } });
expect(hook.setSearchQuery).toHaveBeenCalledWith('kyo');
fireEvent.keyDown(box, { key: 'Escape' });
expect(hook.setSearchQuery).toHaveBeenCalledWith('');
expect(hook.setSearchOpen).toHaveBeenCalledWith(false);
fireEvent.keyDown(box, { key: 'a' });
expect(hook.setSearchOpen).toHaveBeenCalledTimes(1);
});
it('FE-JRN-LISTWIRE-005: an active search reports how many journeys matched', () => {
const journeys = [buildJourney({ id: 1, title: 'Kyoto trip' })];
setup({ journeys, filteredJourneys: journeys, searchQuery: 'kyo' });
expect(screen.getByText('1 journeys')).toBeInTheDocument();
expect(screen.queryByText('All Journeys')).not.toBeInTheDocument();
});
it('FE-JRN-LISTWIRE-006: an empty search result says so', () => {
setup({ journeys: [], filteredJourneys: [], searchQuery: 'zzz' });
expect(screen.getByText(/zzz/)).toBeInTheDocument();
});
it('FE-JRN-LISTWIRE-007: the suggestion banner can be dismissed or turned into a journey', () => {
const { hook } = setup({ activeSuggestion: { id: 42, title: 'Norway 2026' } });
expect(screen.getByText('Trip just ended')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Dismiss' }));
const updater = (hook.setDismissedSuggestions as ReturnType<typeof vi.fn>).mock.calls[0][0] as
(prev: Set<number>) => Set<number>;
expect([...updater(new Set<number>())]).toEqual([42]);
fireEvent.click(screen.getAllByRole('button', { name: 'Create Journey' })[1]);
expect(hook.openCreateModal).toHaveBeenCalledWith(42);
});
it('FE-JRN-LISTWIRE-008: the hero shows the active-journey eyebrow and opens the journey', () => {
const activeJourney = buildJourney({ id: 3, title: 'Norway', subtitle: 'Fjords' });
const { hook } = setup({ activeJourney, activeJourneyIsLive: true, journeys: [activeJourney], filteredJourneys: [] });
expect(screen.getByText('Active Journey')).toBeInTheDocument();
expect(screen.getByText('Fjords')).toBeInTheDocument();
fireEvent.click(screen.getByRole('heading', { name: 'Norway' }));
expect(hook.navigate).toHaveBeenCalledWith('/journey/3');
});
it('FE-JRN-LISTWIRE-009: a non-live hero is labelled as the latest journey and uses its cover', () => {
const activeJourney = buildJourney({ id: 3, title: 'Norway', cover_image: 'covers/n.jpg' });
setup({ activeJourney, activeJourneyIsLive: false, journeys: [activeJourney], filteredJourneys: [] });
expect(screen.getByText('Latest Journey')).toBeInTheDocument();
expect(screen.getByText('Continue writing')).toBeInTheDocument();
});
it('FE-JRN-LISTWIRE-010: a journey card shows its counters and opens on click', () => {
const journey = buildJourney({ id: 5, title: 'Iceland', subtitle: 'Ring road', entry_count: 4, photo_count: 9, place_count: 0, cover_image: 'covers/i.jpg' });
const { hook } = setup({ journeys: [journey], filteredJourneys: [journey] });
expect(screen.getByText('Ring road')).toBeInTheDocument();
expect(screen.getByText('4')).toBeInTheDocument();
expect(screen.getByText('9')).toBeInTheDocument();
expect(screen.getAllByText('--')).toHaveLength(1);
expect(document.querySelector('img[src="/uploads/covers/i.jpg"]')).toBeInTheDocument();
fireEvent.click(screen.getByText('Iceland'));
expect(hook.navigate).toHaveBeenCalledWith('/journey/5');
});
it('FE-JRN-LISTWIRE-011: the dashed create card opens the modal', () => {
const { hook } = setup();
fireEvent.click(screen.getByText('Create a new Journey'));
expect(hook.openCreateModal).toHaveBeenCalledTimes(1);
expect(hook.openCreateModal).toHaveBeenCalledWith();
});
it('FE-JRN-LISTWIRE-012: the spinner replaces the grid on the very first load', () => {
setup({ loading: true, journeys: [], filteredJourneys: [] });
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
expect(screen.queryByText('Create a new Journey')).not.toBeInTheDocument();
});
it('FE-JRN-LISTWIRE-013: the create modal edits name and subtitle and can be cancelled', () => {
const { hook } = setup({ showCreate: true });
fireEvent.change(screen.getByPlaceholderText('e.g. Southeast Asia 2026'), { target: { value: 'Japan' } });
expect(hook.setNewTitle).toHaveBeenCalledWith('Japan');
fireEvent.change(screen.getByPlaceholderText('e.g. Thailand, Vietnam & Cambodia'), { target: { value: 'Tokyo' } });
expect(hook.setNewSubtitle).toHaveBeenCalledWith('Tokyo');
const createButtons = screen.getAllByRole('button', { name: /Create Journey/ });
expect(createButtons[createButtons.length - 1]).toBeDisabled();
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));
expect(hook.setShowCreate).toHaveBeenCalledWith(false);
});
it('FE-JRN-LISTWIRE-014: modal trips render their status and toggle their selection', () => {
const today = new Date().toISOString().split('T')[0];
const availableTrips = [
{ id: 1, title: 'Past trip', start_date: '2020-01-01', end_date: '2020-01-05', place_count: 3, cover_image: '/uploads/t.jpg' },
{ id: 2, title: 'Running trip', start_date: today, end_date: '2099-01-01', place_count: 1 },
{ id: 3, title: 'Future trip', start_date: '2099-01-01', end_date: '2099-01-05', place_count: 0 },
];
const { hook } = setup({ showCreate: true, newTitle: 'Japan', availableTrips, selectedTripIds: new Set([1]), totalPlaces: 3 });
expect(screen.getByText('Completed')).toBeInTheDocument();
expect(screen.getByText('Active')).toBeInTheDocument();
expect(screen.getByText('Upcoming')).toBeInTheDocument();
expect(screen.getByText('places will be imported')).toBeInTheDocument();
fireEvent.click(screen.getByText('Future trip'));
const updater = (hook.setSelectedTripIds as ReturnType<typeof vi.fn>).mock.calls[0][0] as
(prev: Set<number>) => Set<number>;
expect([...updater(new Set<number>([1]))]).toEqual([1, 3]);
expect([...updater(new Set<number>([3]))]).toEqual([]);
const createButtons = screen.getAllByRole('button', { name: /Create Journey/ });
fireEvent.click(createButtons[createButtons.length - 1]);
expect(hook.handleCreate).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,312 @@
// FE-JRN-PUBWIRE-001 to FE-JRN-PUBWIRE-023
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, fireEvent } from '../../tests/helpers/render';
import { useSettingsStore } from '../store/settingsStore';
import { groupByDate, type PublicEntry, type PublicGalleryPhoto } from './journeyPublic/journeyPublicModel';
import JourneyPublicPage from './JourneyPublicPage';
const mocks = vi.hoisted(() => ({
pub: {} as Record<string, unknown>,
captured: {} as Record<string, Record<string, unknown>>,
}));
vi.mock('./journeyPublic/useJourneyPublic', () => ({ useJourneyPublic: () => mocks.pub }));
function capture(name: string, testId: string) {
return (props: Record<string, unknown>) => {
mocks.captured[name] = props;
return <div data-testid={testId} />;
};
}
vi.mock('../components/Journey/JourneyMap', async () => {
const React = await import('react');
const Comp = React.forwardRef((props: Record<string, unknown>, _ref: React.Ref<unknown>) => {
mocks.captured.map = props;
return <div data-testid="public-map" data-height={String(props.height)} />;
});
Comp.displayName = 'MockJourneyMap';
return { __esModule: true, default: Comp };
});
vi.mock('../components/Journey/MobileMapTimeline', () => ({ default: capture('mobileTimeline', 'mobile-timeline') }));
vi.mock('../components/Journey/MobileEntryView', () => ({ default: capture('mobileEntry', 'mobile-entry') }));
vi.mock('../components/Journey/PhotoLightbox', () => ({ default: capture('lightbox', 'lightbox') }));
vi.mock('../components/Journey/JournalBody', () => ({
default: ({ text }: { text: string }) => <div data-testid="journal-body">{text}</div>,
}));
// ── Fixtures ─────────────────────────────────────────────────────────────────
function photo(id: number): PublicEntry['photos'][number] {
return { id, entry_id: 1, photo_id: id * 10, caption: `caption ${id}`, provider: 'local' };
}
function buildEntry(over: Partial<PublicEntry> = {}): PublicEntry {
return {
id: 1, title: 'Arrival', story: null, entry_date: '2026-05-01', entry_time: '09:30',
location_name: 'Tokyo, Japan', location_lat: 35.6, location_lng: 139.7,
mood: null, weather: null, pros_cons: null, photos: [],
...over,
};
}
const highlightMarker = vi.fn();
function buildHook(over: Record<string, unknown> = {}): Record<string, unknown> {
const entries = (over.timelineEntries as PublicEntry[]) ?? [buildEntry()];
const grouped = groupByDate(entries);
return {
token: 'tok-1',
data: { journey: { title: 'Japan 2026' } },
loading: false,
error: false,
isMobile: false,
locale: 'en',
view: 'timeline',
setView: vi.fn(),
lightbox: null,
setLightbox: vi.fn(),
showLangPicker: false,
setShowLangPicker: vi.fn(),
mapRef: { current: { highlightMarker } },
activeEntryId: null,
setActiveEntryId: vi.fn(),
viewingEntry: null,
setViewingEntry: vi.fn(),
handleMarkerClick: vi.fn(),
perms: { share_timeline: true, share_gallery: true, share_map: true },
journey: { title: 'Japan 2026', subtitle: 'Tokyo & Kyoto', cover_image: null },
stats: { entries: 2, photos: 4, places: 3 },
timelineEntries: entries,
groupedEntries: grouped,
sortedDates: [...grouped.keys()].sort(),
sidebarMapItems: [],
allPhotos: [] as PublicGalleryPhoto[],
desktopTwoColumn: true,
...over,
};
}
function setup(over: Record<string, unknown> = {}) {
mocks.pub = buildHook(over);
const view = render(<JourneyPublicPage />);
return { ...view, hook: mocks.pub };
}
const settingsInitial = useSettingsStore.getState();
beforeEach(() => {
vi.clearAllMocks();
mocks.captured = {};
useSettingsStore.setState(settingsInitial, true);
});
// ── Tests ────────────────────────────────────────────────────────────────────
describe('JourneyPublicPage wiring', () => {
it('FE-JRN-PUBWIRE-001: shows a spinner while the share is being fetched', () => {
setup({ loading: true });
expect(document.querySelector('.animate-spin')).toBeInTheDocument();
});
it('FE-JRN-PUBWIRE-002: an unknown or revoked token shows the not-found screen', () => {
setup({ error: true, data: null });
expect(screen.getByRole('heading', { name: 'Not Found' })).toBeInTheDocument();
});
it('FE-JRN-PUBWIRE-003: renders the hero with title, subtitle and stats', () => {
setup();
expect(screen.getByRole('heading', { name: 'Japan 2026' })).toBeInTheDocument();
expect(screen.getByText('Tokyo & Kyoto')).toBeInTheDocument();
expect(screen.getByText(/2 Entries/)).toBeInTheDocument();
expect(screen.getByText(/4 Photos/)).toBeInTheDocument();
expect(screen.getByText(/3 Places/)).toBeInTheDocument();
expect(screen.getByTestId('public-map')).toBeInTheDocument();
});
it('FE-JRN-PUBWIRE-004: the cover image is layered into the hero when present', () => {
setup({ journey: { title: 'Japan 2026', cover_image: 'covers/j.jpg' } });
expect(document.querySelector('[style*="/uploads/covers/j.jpg"]')).toBeInTheDocument();
});
it('FE-JRN-PUBWIRE-005: hovering an entry in two-column mode highlights its marker', () => {
const { hook } = setup();
fireEvent.mouseEnter(document.querySelector('[data-entry-id="1"]')!);
expect(hook.setActiveEntryId).toHaveBeenCalledWith('1');
expect(highlightMarker).toHaveBeenCalledWith('1');
});
it('FE-JRN-PUBWIRE-006: in single-column mode hovering does nothing', () => {
const { hook } = setup({ desktopTwoColumn: false });
fireEvent.mouseEnter(document.querySelector('[data-entry-id="1"]')!);
expect(hook.setActiveEntryId).not.toHaveBeenCalled();
expect(highlightMarker).not.toHaveBeenCalled();
});
it('FE-JRN-PUBWIRE-007: an active entry gets the day-colour outline', () => {
setup({ activeEntryId: '1' });
expect(document.querySelector('[data-entry-id="1"]')).toHaveStyle({ borderRadius: '16px' });
});
it('FE-JRN-PUBWIRE-008: a single-photo entry opens the lightbox and overlays its title', () => {
const { hook } = setup({ timelineEntries: [buildEntry({ photos: [photo(1)] })] });
expect(screen.getByText('Tokyo, Japan')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Arrival' })).toBeInTheDocument();
// the hero photo of a single-photo entry is served at full size
fireEvent.click(document.querySelector('img[src="/api/public/journey/tok-1/photos/10/original"]')!.parentElement!);
expect(hook.setLightbox).toHaveBeenCalledWith({
index: 0,
photos: [expect.objectContaining({ id: '1', src: '/api/public/journey/tok-1/photos/10/original' })],
});
});
it('FE-JRN-PUBWIRE-009: a two-photo entry opens the lightbox at the clicked index', () => {
const { hook } = setup({ timelineEntries: [buildEntry({ photos: [photo(1), photo(2)] })] });
fireEvent.click(document.querySelector('img[src="/api/public/journey/tok-1/photos/20/thumbnail"]')!);
expect(hook.setLightbox).toHaveBeenCalledWith(expect.objectContaining({ index: 1 }));
});
it('FE-JRN-PUBWIRE-010: a four-photo entry shows the +N overlay and three click targets', () => {
const { hook } = setup({
timelineEntries: [buildEntry({ photos: [photo(1), photo(2), photo(3), photo(4)] })],
});
expect(screen.getByText('+1')).toBeInTheDocument();
for (const [photoId, index] of [[10, 0], [20, 1], [30, 2]] as const) {
fireEvent.click(document.querySelector(`img[src="/api/public/journey/tok-1/photos/${photoId}/thumbnail"]`)!.parentElement!);
expect(hook.setLightbox).toHaveBeenLastCalledWith(expect.objectContaining({ index }));
}
});
it('FE-JRN-PUBWIRE-011: tapping the text body opens the entry detail view', () => {
const { hook } = setup({ timelineEntries: [buildEntry({ story: 'A long day.' })] });
expect(screen.getByTestId('journal-body')).toHaveTextContent('A long day.');
expect(screen.getByText('09:30')).toBeInTheDocument();
fireEvent.click(screen.getByTestId('journal-body'));
expect(hook.setViewingEntry).toHaveBeenCalledWith(expect.objectContaining({ id: 1 }));
});
it('FE-JRN-PUBWIRE-012: pros, cons, mood and weather are rendered', () => {
setup({
timelineEntries: [buildEntry({
mood: 'amazing',
weather: 'rainy',
pros_cons: { pros: ['Great food', 'Friendly'], cons: ['Crowded'] },
})],
});
expect(screen.getByText('Great food')).toBeInTheDocument();
expect(screen.getByText('Friendly')).toBeInTheDocument();
expect(screen.getByText('Crowded')).toBeInTheDocument();
expect(screen.getByText('Amazing')).toBeInTheDocument();
expect(screen.getByText('Rainy')).toBeInTheDocument();
});
it('FE-JRN-PUBWIRE-013: a share without entries shows the empty state', () => {
setup({ timelineEntries: [] });
expect(screen.getByText('No entries yet')).toBeInTheDocument();
});
it('FE-JRN-PUBWIRE-014: the gallery opens the lightbox over all photos and flags videos', () => {
const allPhotos = [
{ id: 1, journey_id: 7, photo_id: 100, caption: 'a' },
{ id: 2, journey_id: 7, photo_id: 101, caption: null, media_type: 'video' },
];
const { hook } = setup({ view: 'gallery', allPhotos });
const tiles = document.querySelectorAll('img[src^="/api/public/journey/tok-1/photos/"]');
expect(tiles).toHaveLength(2);
fireEvent.click(tiles[1].parentElement!);
expect(hook.setLightbox).toHaveBeenCalledWith({
index: 1,
photos: [
expect.objectContaining({ id: '1', src: '/api/public/journey/tok-1/photos/100/original' }),
expect.objectContaining({ id: '2', mediaType: 'video' }),
],
});
});
it('FE-JRN-PUBWIRE-015: the language picker switches the stored UI language', () => {
const { hook } = setup({ showLangPicker: true });
const german = screen.getByRole('button', { name: 'Deutsch' });
fireEvent.mouseEnter(german);
expect(german).toHaveStyle({ background: 'rgb(243, 244, 246)' });
fireEvent.mouseLeave(german);
fireEvent.click(german);
expect(useSettingsStore.getState().settings.language).toBe('de');
expect(hook.setShowLangPicker).toHaveBeenCalledWith(false);
});
it('FE-JRN-PUBWIRE-016: the picker button toggles the dropdown', () => {
const { hook } = setup();
expect(screen.queryByRole('button', { name: 'Deutsch' })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'English' }));
const toggle = (hook.setShowLangPicker as ReturnType<typeof vi.fn>).mock.calls[0][0] as (v: boolean) => boolean;
expect(toggle(false)).toBe(true);
});
it('FE-JRN-PUBWIRE-017: the tab bar switches between timeline and gallery', () => {
const { hook } = setup();
fireEvent.click(screen.getByRole('button', { name: /Gallery/ }));
expect(hook.setView).toHaveBeenCalledWith('gallery');
});
it('FE-JRN-PUBWIRE-018: single-column mode offers the standalone map tab', () => {
setup({ desktopTwoColumn: false, view: 'map' });
expect(screen.getByTestId('public-map')).toHaveAttribute('data-height', '500');
expect(screen.getByRole('button', { name: /Map/ })).toBeInTheDocument();
});
it('FE-JRN-PUBWIRE-019: on mobile the combined map timeline takes over with public photo URLs', () => {
const { hook } = setup({ isMobile: true, desktopTwoColumn: false });
expect(screen.getByTestId('mobile-timeline')).toBeInTheDocument();
const publicPhotoUrl = mocks.captured.mobileTimeline.publicPhotoUrl as (id: number) => string;
expect(publicPhotoUrl(55)).toBe('/api/public/journey/tok-1/photos/55/original');
(mocks.captured.mobileTimeline.onEntryClick as (e: PublicEntry) => void)(buildEntry({ id: 9 }));
expect(hook.setViewingEntry).toHaveBeenCalledWith(expect.objectContaining({ id: 9 }));
});
it('FE-JRN-PUBWIRE-020: the floating mobile toggle switches the view', () => {
const { hook } = setup({ isMobile: true, desktopTwoColumn: false });
const galleryButtons = screen.getAllByRole('button', { name: /Gallery/ });
fireEvent.click(galleryButtons[0]);
expect(hook.setView).toHaveBeenCalledWith('gallery');
});
it('FE-JRN-PUBWIRE-021: the mobile entry view maps its photos into the lightbox', () => {
const viewingEntry = buildEntry({ id: 9 });
const { hook } = setup({ isMobile: true, desktopTwoColumn: false, viewingEntry });
expect(screen.getByTestId('mobile-entry')).toBeInTheDocument();
const publicPhotoUrl = mocks.captured.mobileEntry.publicPhotoUrl as (id: number) => string;
expect(publicPhotoUrl(77)).toBe('/api/public/journey/tok-1/photos/77/original');
const onPhotoClick = mocks.captured.mobileEntry.onPhotoClick as (p: Record<string, unknown>[], i: number) => void;
onPhotoClick([{ id: 3, photo_id: 30, caption: 'x', media_type: 'image' }], 0);
expect(hook.setLightbox).toHaveBeenCalledWith({
index: 0,
photos: [expect.objectContaining({ id: '3', src: '/api/public/journey/tok-1/photos/30/original', caption: 'x' })],
});
(mocks.captured.mobileEntry.onClose as () => void)();
expect(hook.setViewingEntry).toHaveBeenCalledWith(null);
});
it('FE-JRN-PUBWIRE-022: the lightbox closes back into the hook', () => {
const { hook } = setup({ lightbox: { photos: [{ id: '1', src: '/x', caption: null }], index: 0 } });
expect(screen.getByTestId('lightbox')).toBeInTheDocument();
(mocks.captured.lightbox.onClose as () => void)();
expect(hook.setLightbox).toHaveBeenCalledWith(null);
});
it('FE-JRN-PUBWIRE-023: a timeline-only share hides the tab bar entirely', () => {
setup({ perms: { share_timeline: true, share_gallery: false, share_map: false }, desktopTwoColumn: false });
expect(screen.queryByRole('button', { name: /Gallery/ })).not.toBeInTheDocument();
expect(screen.getByText('Arrival')).toBeInTheDocument();
});
});
+521
View File
@@ -0,0 +1,521 @@
// FE-LOGIN-WIRE-001 to FE-LOGIN-WIRE-024
//
// LoginPage is a wiring container (see client/scripts/check-page-pattern.mjs): the
// behaviour lives in useLogin. These tests stub the hook and drive the markup
// directly, which is the only way to reach the states the hook rarely produces
// (OIDC-only, passkeys, forced password change) and the presentation handlers.
import React from 'react';
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { render, screen, fireEvent } from '../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../tests/helpers/store';
import { useSettingsStore } from '../store/settingsStore';
import LoginPage from './LoginPage';
import { useLogin } from './login/useLogin';
vi.mock('./login/useLogin', () => ({ useLogin: vi.fn() }));
vi.mock('./login/LoginWorld', () => ({
default: ({ variant }: { variant?: string }) => <div data-testid="login-world" data-variant={variant ?? 'ambient'} />,
}));
const EMAIL_PLACEHOLDER = 'your@email.com';
const PASSWORD_PLACEHOLDER = '••••••••';
function makeFixture() {
return {
navigate: vi.fn(),
mode: 'login' as 'login' | 'register',
setMode: vi.fn(),
username: '',
setUsername: vi.fn(),
email: '',
setEmail: vi.fn(),
password: '',
setPassword: vi.fn(),
rememberMe: false,
setRememberMe: vi.fn(),
showPassword: false,
setShowPassword: vi.fn(),
isLoading: false,
error: '',
setError: vi.fn(),
insecureCookie: false,
appConfig: {
has_users: true,
allow_registration: true,
setup_complete: true,
demo_mode: false,
oidc_configured: false,
oidc_display_name: undefined as string | undefined,
oidc_only_mode: false,
password_login: true,
password_registration: true,
oidc_login: false,
oidc_registration: false,
passkey_login: false,
passkey_configured: false,
env_override_oidc_only: false,
},
inviteToken: '',
langDropdownOpen: false,
setLangDropdownOpen: vi.fn(),
setLanguageLocal: vi.fn(),
showTakeoff: false,
mfaStep: false,
setMfaStep: vi.fn(),
mfaToken: '',
setMfaToken: vi.fn(),
mfaCode: '',
setMfaCode: vi.fn(),
passwordChangeStep: false,
newPassword: '',
setNewPassword: vi.fn(),
confirmPassword: '',
setConfirmPassword: vi.fn(),
noRedirect: false,
showRegisterOption: true,
oidcOnly: false,
handleDemoLogin: vi.fn(async () => {}),
handleSubmit: vi.fn(async (_e: React.FormEvent<HTMLFormElement>) => {}),
handlePasskeyLogin: vi.fn(async () => {}),
};
}
type Fixture = ReturnType<typeof makeFixture>;
let fixture: Fixture;
function renderPage(f: Fixture = fixture) {
vi.mocked(useLogin).mockReturnValue(f as unknown as ReturnType<typeof useLogin>);
return render(<LoginPage />);
}
/** Both hover handlers on an element, asserting the leave handler restores the entry state. */
function hoverRoundTrip(el: HTMLElement, prop: 'background' | 'transform' | 'color' | 'borderColor') {
const before = el.style[prop];
fireEvent.mouseEnter(el);
const hovered = el.style[prop];
fireEvent.mouseLeave(el);
return { before, hovered, after: el.style[prop] };
}
beforeEach(() => {
resetAllStores();
fixture = makeFixture();
});
describe('LoginPage — takeoff', () => {
it('FE-LOGIN-WIRE-001: replaces the form with the takeoff world and the tagline', () => {
fixture.showTakeoff = true;
renderPage();
expect(document.querySelector('.takeoff-overlay')).toBeInTheDocument();
expect(screen.getByTestId('login-world')).toHaveAttribute('data-variant', 'takeoff');
expect(screen.getByAltText('TREK')).toHaveAttribute('src', '/logo-light.svg');
expect(screen.queryByPlaceholderText(EMAIL_PLACEHOLDER)).toBeNull();
});
});
describe('LoginPage — language switcher', () => {
it('FE-LOGIN-WIRE-002: the globe button toggles the dropdown without closing it again', () => {
renderPage();
const button = screen.getByRole('button', { name: 'Change language' });
expect(button).toHaveAttribute('aria-expanded', 'false');
expect(button).toHaveTextContent('English');
fireEvent.click(button);
const toggle = vi.mocked(fixture.setLangDropdownOpen).mock.calls[0][0] as (open: boolean) => boolean;
expect(toggle(false)).toBe(true);
expect(toggle(true)).toBe(false);
});
it('FE-LOGIN-WIRE-003: the globe button reacts to hover', () => {
renderPage();
const { before, hovered, after } = hoverRoundTrip(
screen.getByRole('button', { name: 'Change language' }),
'background',
);
expect(hovered).not.toBe(before);
expect(after).toBe(before);
});
it('FE-LOGIN-WIRE-034: falls back to the bare code when the stored language has no label', () => {
seedStore(useSettingsStore, { settings: { language: 'xx' } });
renderPage();
expect(screen.getByRole('button', { name: 'Change language' })).toHaveTextContent('XX');
});
it('FE-LOGIN-WIRE-004: the open dropdown lists every language and marks the active one', () => {
fixture.langDropdownOpen = true;
renderPage();
expect(screen.getByRole('button', { name: 'Change language' })).toHaveAttribute('aria-expanded', 'true');
const options = screen.getAllByRole('option');
expect(options).toHaveLength(23);
expect(screen.getByRole('option', { name: 'Deutsch' })).toHaveAttribute('aria-selected', 'false');
expect(screen.getByRole('option', { name: 'English' })).toHaveAttribute('aria-selected', 'true');
});
it('FE-LOGIN-WIRE-005: picking a language applies it and closes the dropdown', () => {
fixture.langDropdownOpen = true;
renderPage();
fireEvent.click(screen.getByRole('option', { name: 'Français' }));
expect(fixture.setLanguageLocal).toHaveBeenCalledWith('fr');
expect(fixture.setLangDropdownOpen).toHaveBeenCalledWith(false);
});
it('FE-LOGIN-WIRE-006: clicks inside the dropdown never reach the document closer', () => {
fixture.langDropdownOpen = true;
renderPage();
const documentClick = vi.fn();
document.addEventListener('click', documentClick);
fireEvent.click(screen.getByRole('option', { name: 'Español' }));
expect(fixture.setLanguageLocal).toHaveBeenCalledWith('es');
expect(documentClick).not.toHaveBeenCalled();
document.removeEventListener('click', documentClick);
});
it('FE-LOGIN-WIRE-007: hover highlights an inactive option and leaves the active one alone', () => {
fixture.langDropdownOpen = true;
renderPage();
const inactive = hoverRoundTrip(screen.getByRole('option', { name: 'Italiano' }), 'background');
expect(inactive.hovered).not.toBe(inactive.before);
expect(inactive.after).toBe(inactive.before);
const active = hoverRoundTrip(screen.getByRole('option', { name: 'English' }), 'background');
expect(active.hovered).toBe(active.before);
expect(active.after).toBe(active.before);
});
});
describe('LoginPage — OIDC-only mode', () => {
it('FE-LOGIN-WIRE-008: offers only the SSO link, named after the provider', () => {
fixture.oidcOnly = true;
fixture.appConfig.oidc_display_name = 'Authentik';
renderPage();
expect(screen.queryByPlaceholderText(EMAIL_PLACEHOLDER)).toBeNull();
const link = screen.getByRole('link', { name: /sign in with authentik/i });
expect(link).toHaveAttribute('href', '/api/auth/oidc/login');
expect(
screen.getByText('Password authentication is disabled. Please sign in using your SSO provider.'),
).toBeInTheDocument();
});
it('FE-LOGIN-WIRE-009: explains the logout and carries the invite token into the SSO link', () => {
fixture.oidcOnly = true;
fixture.noRedirect = true;
fixture.inviteToken = 'inv/42';
fixture.error = 'Invalid session. Please try again.';
renderPage();
expect(
screen.getByText('You have been logged out. Sign in again using your SSO provider.'),
).toBeInTheDocument();
expect(screen.getByText('Invalid session. Please try again.')).toBeInTheDocument();
expect(screen.getByRole('link', { name: /sign in with sso/i })).toHaveAttribute(
'href',
'/api/auth/oidc/login?invite=inv%2F42',
);
});
it('FE-LOGIN-WIRE-010: the SSO button darkens on hover', () => {
fixture.oidcOnly = true;
renderPage();
const { before, hovered, after } = hoverRoundTrip(
screen.getByRole('link', { name: /sign in with sso/i }),
'background',
);
expect(hovered).not.toBe(before);
expect(after).toBe(before);
});
});
describe('LoginPage — password form', () => {
it('FE-LOGIN-WIRE-011: the eye button flips the password visibility', () => {
renderPage();
const input = screen.getByPlaceholderText(PASSWORD_PLACEHOLDER);
expect(input).toHaveAttribute('type', 'password');
const buttons = screen.getAllByRole('button');
const toggle = buttons.find((b) => b.getAttribute('type') === 'button' && b.querySelector('svg') && b.style.right === '12px')!;
fireEvent.click(toggle);
const updater = vi.mocked(fixture.setShowPassword).mock.calls[0][0] as (v: boolean) => boolean;
expect(updater(false)).toBe(true);
});
it('FE-LOGIN-WIRE-012: showPassword renders the value in clear text', () => {
fixture.showPassword = true;
fixture.password = 'hunter2';
renderPage();
expect(screen.getByDisplayValue('hunter2')).toHaveAttribute('type', 'text');
});
it('FE-LOGIN-WIRE-013: the remember-me label toggles the switch', () => {
renderPage();
fireEvent.click(screen.getByText('Remember me', { selector: 'span' }));
expect(fixture.setRememberMe).toHaveBeenCalledWith(true);
fireEvent.click(screen.getByRole('button', { name: 'Remember me' }));
expect(fixture.setRememberMe).toHaveBeenCalledTimes(2);
});
it('FE-LOGIN-WIRE-014: the forgot-password link routes and highlights on hover', () => {
renderPage();
const button = screen.getByRole('button', { name: /forgot password/i });
const { before, hovered, after } = hoverRoundTrip(button, 'color');
expect(hovered).not.toBe(before);
expect(after).toBe(before);
fireEvent.click(button);
expect(fixture.navigate).toHaveBeenCalledWith('/forgot-password');
});
it('FE-LOGIN-WIRE-015: submitting the form goes through the hook', () => {
renderPage();
fireEvent.submit(document.querySelector('form')!);
expect(fixture.handleSubmit).toHaveBeenCalled();
});
it('FE-LOGIN-WIRE-016: the loading state disables the submit button and swaps the label', () => {
fixture.isLoading = true;
renderPage();
const submit = screen.getByRole('button', { name: /signing in/i });
expect(submit).toBeDisabled();
expect(submit.style.cursor).toBe('default');
expect(submit.style.opacity).toBe('0.7');
});
it('FE-LOGIN-WIRE-017: the warning banner explains a dropped Secure cookie', () => {
fixture.insecureCookie = true;
renderPage();
expect(screen.getByText("Login won't stick over HTTP")).toBeInTheDocument();
expect(screen.getByRole('link', { name: /troubleshooting/i })).toHaveAttribute(
'href',
'https://github.com/liketrek/TREK/wiki/Troubleshooting',
);
});
});
describe('LoginPage — MFA step', () => {
beforeEach(() => {
fixture.mfaStep = true;
fixture.mfaToken = 'mfa-tok';
});
it('FE-LOGIN-WIRE-018: shows only the code field and normalises what is typed', () => {
renderPage();
expect(screen.getByText('Two-factor authentication')).toBeInTheDocument();
expect(screen.queryByPlaceholderText(EMAIL_PLACEHOLDER)).toBeNull();
const input = screen.getByPlaceholderText('000000 or XXXX-XXXX');
fireEvent.change(input, { target: { value: 'abcd-efgh' } });
expect(fixture.setMfaCode).toHaveBeenCalledWith('ABCD-EFGH');
fireEvent.change(input, { target: { value: 'x'.repeat(40) } });
expect(fixture.setMfaCode).toHaveBeenLastCalledWith('X'.repeat(24));
});
it('FE-LOGIN-WIRE-019: the back link drops the pending MFA challenge', () => {
renderPage();
fireEvent.click(screen.getByRole('button', { name: /back to sign in/i }));
expect(fixture.setMfaStep).toHaveBeenCalledWith(false);
expect(fixture.setMfaToken).toHaveBeenCalledWith('');
expect(fixture.setMfaCode).toHaveBeenCalledWith('');
expect(fixture.setError).toHaveBeenCalledWith('');
});
it('FE-LOGIN-WIRE-020: the submit button verifies instead of signing in', () => {
fixture.isLoading = true;
renderPage();
expect(screen.getByRole('button', { name: /verify/i })).toBeDisabled();
});
});
describe('LoginPage — forced password change', () => {
beforeEach(() => {
fixture.passwordChangeStep = true;
});
it('FE-LOGIN-WIRE-021: swaps the form for the two new-password fields', () => {
renderPage();
expect(screen.getByText(/You must change your password before you can continue/)).toBeInTheDocument();
expect(screen.queryByPlaceholderText(EMAIL_PLACEHOLDER)).toBeNull();
expect(screen.queryByPlaceholderText(PASSWORD_PLACEHOLDER)).toBeNull();
fireEvent.change(screen.getByPlaceholderText('New password'), { target: { value: 'newpassword123' } });
expect(fixture.setNewPassword).toHaveBeenCalledWith('newpassword123');
fireEvent.change(screen.getByPlaceholderText('Confirm new password'), { target: { value: 'newpassword123' } });
expect(fixture.setConfirmPassword).toHaveBeenCalledWith('newpassword123');
});
it('FE-LOGIN-WIRE-022: hides the register toggle and labels the button "Update password"', () => {
fixture.isLoading = true;
renderPage();
expect(screen.getByRole('button', { name: /update password/i })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /^register$/i })).toBeNull();
});
});
describe('LoginPage — register mode', () => {
it('FE-LOGIN-WIRE-023: switching to register resets the pending MFA state', () => {
renderPage();
fireEvent.click(screen.getByRole('button', { name: /^register$/i }));
const updater = vi.mocked(fixture.setMode).mock.calls[0][0] as (m: 'login' | 'register') => 'login' | 'register';
expect(updater('login')).toBe('register');
expect(updater('register')).toBe('login');
expect(fixture.setError).toHaveBeenCalledWith('');
expect(fixture.setMfaStep).toHaveBeenCalledWith(false);
expect(fixture.setMfaToken).toHaveBeenCalledWith('');
expect(fixture.setMfaCode).toHaveBeenCalledWith('');
});
it('FE-LOGIN-WIRE-024: asks for an admin account on a fresh instance', () => {
fixture.mode = 'register';
fixture.appConfig.has_users = false;
renderPage();
expect(screen.getByRole('heading', { name: 'Create Admin Account' })).toBeInTheDocument();
fireEvent.change(screen.getByPlaceholderText('admin'), { target: { value: 'root' } });
expect(fixture.setUsername).toHaveBeenCalledWith('root');
// No users yet means no "already have an account?" toggle.
expect(screen.queryByRole('button', { name: /^sign in$/i })).toBeNull();
});
it('FE-LOGIN-WIRE-025: shows the creating label while the account is being made', () => {
fixture.mode = 'register';
fixture.isLoading = true;
renderPage();
expect(screen.getByRole('button', { name: /creating/i })).toBeDisabled();
});
});
describe('LoginPage — alternative sign-in buttons', () => {
it('FE-LOGIN-WIRE-026: the SSO button sits behind an "or" divider and reacts to hover', () => {
fixture.appConfig.oidc_configured = true;
fixture.appConfig.oidc_login = true;
fixture.appConfig.oidc_display_name = 'Keycloak';
fixture.inviteToken = 'abc';
renderPage();
expect(screen.getByText('or')).toBeInTheDocument();
const link = screen.getByRole('link', { name: /sign in with keycloak/i });
expect(link).toHaveAttribute('href', '/api/auth/oidc/login?invite=abc');
const background = hoverRoundTrip(link, 'background');
expect(background.hovered).not.toBe(background.before);
expect(background.after).toBe(background.before);
});
it('FE-LOGIN-WIRE-027: the passkey button signs in and reacts to hover', () => {
fixture.appConfig.passkey_login = true;
fixture.appConfig.passkey_configured = true;
renderPage();
const button = screen.getByRole('button', { name: /sign in with a passkey/i });
// No SSO button, so the passkey button brings its own divider.
expect(screen.getByText('or')).toBeInTheDocument();
const background = hoverRoundTrip(button, 'background');
expect(background.hovered).not.toBe(background.before);
expect(background.after).toBe(background.before);
fireEvent.click(button);
expect(fixture.handlePasskeyLogin).toHaveBeenCalled();
});
it('FE-LOGIN-WIRE-028: the passkey button borrows the SSO divider instead of adding a second one', () => {
fixture.appConfig.oidc_configured = true;
fixture.appConfig.oidc_login = true;
fixture.appConfig.passkey_login = true;
fixture.appConfig.passkey_configured = true;
renderPage();
expect(screen.getAllByText('or')).toHaveLength(1);
expect(screen.getByRole('button', { name: /sign in with a passkey/i })).toBeInTheDocument();
});
it('FE-LOGIN-WIRE-029: the passkey button is inert while a sign-in is running', () => {
fixture.appConfig.passkey_login = true;
fixture.appConfig.passkey_configured = true;
fixture.isLoading = true;
renderPage();
const button = screen.getByRole('button', { name: /sign in with a passkey/i });
expect(button).toBeDisabled();
expect(button.style.cursor).toBe('default');
expect(button.style.opacity).toBe('0.7');
fireEvent.click(button);
expect(fixture.handlePasskeyLogin).not.toHaveBeenCalled();
});
it('FE-LOGIN-WIRE-030: passkeys stay hidden during the MFA and password-change steps', () => {
fixture.appConfig.passkey_login = true;
fixture.appConfig.passkey_configured = true;
fixture.mfaStep = true;
renderPage();
expect(screen.queryByRole('button', { name: /sign in with a passkey/i })).toBeNull();
});
it('FE-LOGIN-WIRE-031: the demo button lifts on hover and starts the demo login', () => {
fixture.appConfig.demo_mode = true;
renderPage();
const button = screen.getByRole('button', { name: /try the demo/i });
const { before, hovered, after } = hoverRoundTrip(button, 'transform');
expect(hovered).toBe('translateY(-1px)');
expect(before).toBe('');
expect(after).toBe('translateY(0)');
fireEvent.click(button);
expect(fixture.handleDemoLogin).toHaveBeenCalled();
});
it('FE-LOGIN-WIRE-032: the demo button is inert while a login is running', () => {
fixture.appConfig.demo_mode = true;
fixture.isLoading = true;
renderPage();
const button = screen.getByRole('button', { name: /try the demo/i });
expect(button).toBeDisabled();
expect(button.style.cursor).toBe('default');
expect(button.style.opacity).toBe('0.7');
fireEvent.click(button);
expect(fixture.handleDemoLogin).not.toHaveBeenCalled();
});
it('FE-LOGIN-WIRE-033: demo instances hide the register toggle', () => {
fixture.appConfig.demo_mode = true;
renderPage();
expect(screen.queryByRole('button', { name: /^register$/i })).toBeNull();
});
});
+188
View File
@@ -0,0 +1,188 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import type { FormEvent } from 'react'
import { render, screen, fireEvent } from '../../tests/helpers/render'
import ResetPasswordPage from './ResetPasswordPage'
// FE-PAGE-RESETUI-001 to FE-PAGE-RESETUI-010
//
// ResetPasswordPage is a wiring container over useResetPassword (covered in
// resetPassword/useResetPassword.test.ts). The hook is mocked so the success,
// broken-link, password and MFA screens can each be rendered directly.
const mocks = vi.hoisted(() => ({ reset: {} as Record<string, unknown> }))
vi.mock('./resetPassword/useResetPassword', () => ({ useResetPassword: () => mocks.reset }))
const navigate = vi.fn((_to: string) => {})
const setPw = vi.fn((_v: string) => {})
const setPw2 = vi.fn((_v: string) => {})
const setShowPw = vi.fn((_v: boolean | ((p: boolean) => boolean)) => {})
const setMfaCode = vi.fn((_v: string) => {})
const handleSubmit = vi.fn(async (_e: FormEvent) => {})
function setReset(over: Record<string, unknown> = {}) {
mocks.reset = {
navigate,
token: 'tok-1',
pw: '',
setPw,
pw2: '',
setPw2,
showPw: false,
setShowPw,
mfaCode: '',
setMfaCode,
mfaRequired: false,
error: '',
success: false,
isLoading: false,
handleSubmit,
...over,
}
}
beforeEach(() => {
vi.clearAllMocks()
setReset()
})
describe('ResetPasswordPage', () => {
it('FE-PAGE-RESETUI-001: renders the password form for a valid token', () => {
setReset()
render(<ResetPasswordPage />)
expect(screen.getByRole('heading', { name: 'Set a new password' })).toBeInTheDocument()
expect(screen.getByText(/Pick a strong password/)).toBeInTheDocument()
expect(screen.getByText('New password')).toBeInTheDocument()
expect(screen.getByText('Confirm new password')).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Reset password' })).toBeEnabled()
expect(screen.queryByText('2FA code')).toBeNull()
})
it('FE-PAGE-RESETUI-002: typing into both password fields is reported upwards', () => {
setReset({ pw: 'abc', pw2: 'abd' })
render(<ResetPasswordPage />)
const [pwInput, pw2Input] = screen.getAllByPlaceholderText('••••••••')
expect(pwInput).toHaveValue('abc')
expect(pw2Input).toHaveValue('abd')
fireEvent.change(pwInput, { target: { value: 'abcd' } })
expect(setPw).toHaveBeenCalledWith('abcd')
fireEvent.change(pw2Input, { target: { value: 'abcde' } })
expect(setPw2).toHaveBeenCalledWith('abcde')
})
it('FE-PAGE-RESETUI-003: submitting the form delegates to the hook', () => {
setReset({ pw: 'longenough', pw2: 'longenough' })
render(<ResetPasswordPage />)
fireEvent.submit(screen.getByRole('button', { name: 'Reset password' }).closest('form') as HTMLFormElement)
expect(handleSubmit).toHaveBeenCalled()
})
it('FE-PAGE-RESETUI-004: the reveal toggle flips the input type and asks for the opposite state', () => {
setReset()
const { rerender } = render(<ResetPasswordPage />)
const [pwInput] = screen.getAllByPlaceholderText('••••••••')
expect(pwInput).toHaveAttribute('type', 'password')
const toggle = pwInput.parentElement?.querySelector('button') as HTMLButtonElement
fireEvent.click(toggle)
expect(setShowPw).toHaveBeenCalled()
const updater = setShowPw.mock.calls[0][0] as (p: boolean) => boolean
expect(updater(false)).toBe(true)
setReset({ showPw: true })
rerender(<ResetPasswordPage />)
expect(screen.getAllByPlaceholderText('••••••••')[0]).toHaveAttribute('type', 'text')
})
it('FE-PAGE-RESETUI-005: focusing and blurring an input swaps its border colour', () => {
setReset()
render(<ResetPasswordPage />)
const [pwInput, pw2Input] = screen.getAllByPlaceholderText('••••••••')
fireEvent.focus(pwInput)
expect((pwInput as HTMLInputElement).style.borderColor).toBe('rgb(17, 24, 39)')
fireEvent.blur(pwInput)
expect((pwInput as HTMLInputElement).style.borderColor).toBe('rgb(229, 231, 235)')
fireEvent.focus(pw2Input)
expect((pw2Input as HTMLInputElement).style.borderColor).toBe('rgb(17, 24, 39)')
fireEvent.blur(pw2Input)
expect((pw2Input as HTMLInputElement).style.borderColor).toBe('rgb(229, 231, 235)')
})
it('FE-PAGE-RESETUI-006: an error from the hook is shown above the form', () => {
setReset({ error: "Passwords don't match" })
render(<ResetPasswordPage />)
expect(screen.getByText("Passwords don't match")).toBeInTheDocument()
// The form is still there so the user can correct the input.
expect(screen.getByRole('button', { name: 'Reset password' })).toBeInTheDocument()
})
it('FE-PAGE-RESETUI-007: the MFA step replaces the password fields with a code field', () => {
setReset({ mfaRequired: true, mfaCode: '12' })
render(<ResetPasswordPage />)
expect(screen.getByText(/Enter your 2FA code/)).toBeInTheDocument()
expect(screen.queryByPlaceholderText('••••••••')).toBeNull()
const codeInput = screen.getByPlaceholderText('123456 or backup-code')
expect(codeInput).toHaveValue('12')
fireEvent.change(codeInput, { target: { value: '123' } })
expect(setMfaCode).toHaveBeenCalledWith('123')
fireEvent.focus(codeInput)
expect((codeInput as HTMLInputElement).style.borderColor).toBe('rgb(17, 24, 39)')
fireEvent.blur(codeInput)
expect((codeInput as HTMLInputElement).style.borderColor).toBe('rgb(229, 231, 235)')
expect(screen.getByRole('button', { name: 'Verify & reset' })).toBeInTheDocument()
})
it('FE-PAGE-RESETUI-008: a running submit disables the button and swaps its label', () => {
setReset({ isLoading: true })
render(<ResetPasswordPage />)
const btn = screen.getByRole('button', { name: '…' })
expect(btn).toBeDisabled()
expect(btn.style.opacity).toBe('0.7')
expect(btn.style.cursor).toBe('default')
})
it('FE-PAGE-RESETUI-009: a successful reset shows the confirmation and links back to sign in', () => {
setReset({ success: true })
render(<ResetPasswordPage />)
expect(screen.getByRole('heading', { name: 'Password updated' })).toBeInTheDocument()
expect(screen.getByText('You can now sign in with your new password.')).toBeInTheDocument()
expect(screen.queryByRole('form')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Sign In' }))
expect(navigate).toHaveBeenCalledWith('/login')
})
it('FE-PAGE-RESETUI-010: a missing token shows the broken-link screen instead of the form', () => {
setReset({ token: '', error: 'Invalid reset link' })
render(<ResetPasswordPage />)
expect(screen.getByRole('heading', { name: 'Invalid reset link' })).toBeInTheDocument()
expect(screen.getByText(/This link is missing or broken/)).toBeInTheDocument()
expect(screen.queryByPlaceholderText('••••••••')).toBeNull()
fireEvent.click(screen.getByRole('button', { name: 'Send reset link' }))
expect(navigate).toHaveBeenCalledWith('/forgot-password')
})
it('FE-PAGE-RESETUI-011: the success screen wins over a missing token', () => {
setReset({ token: '', success: true })
render(<ResetPasswordPage />)
expect(screen.getByRole('heading', { name: 'Password updated' })).toBeInTheDocument()
expect(screen.queryByText('Invalid reset link')).toBeNull()
})
})
+567
View File
@@ -572,4 +572,571 @@ describe('SharedTripPage', () => {
await waitFor(() => expect(screen.getAllByText(/125\.00 NZD/).length).toBeGreaterThan(0));
});
});
// FE-PAGE-SHARED-021 to FE-PAGE-SHARED-036 drive the remaining render branches of
// the page: header variants, the permission-driven tab strip, and every item kind
// the day timeline, bookings, packing, costs and chat sections can produce.
const ALL_TABS = { share_bookings: true, share_packing: true, share_budget: true, share_collab: true };
function payload(over: Record<string, unknown> = {}) {
return {
trip: { id: 1, title: 'Shared Paris Trip' },
days: [],
assignments: {},
dayNotes: {},
places: [],
reservations: [],
accommodations: [],
packing: [],
budget: [],
categories: [],
permissions: { share_bookings: false, share_packing: false, share_budget: false, share_collab: false },
collab: [],
...over,
};
}
/** Serve one payload for `token`; anything else falls through to the default handler. */
function serve(token: string, body: Record<string, unknown>) {
server.use(
http.get('/api/shared/:token', ({ params }) => (params.token === token ? HttpResponse.json(body) : undefined)),
);
}
async function open(token: string, body: Record<string, unknown>) {
serve(token, body);
renderSharedTrip(token);
await waitFor(() => expect(screen.getByText('Shared Paris Trip')).toBeInTheDocument());
}
function coverStyle(): string {
const layer = document.querySelector('div[style*="background-image"]') as HTMLElement | null;
return layer?.style.backgroundImage ?? '';
}
/** The page formats dates through the active locale (en-US in tests). */
const fmtDate = (iso: string, opts: Intl.DateTimeFormatOptions) =>
new Date(iso).toLocaleDateString('en-US', opts);
describe('FE-PAGE-SHARED-021: cover image, description and date range in the header', () => {
it('uses an absolute cover URL unchanged and renders the description', async () => {
await open('cover-http-token', payload({
trip: {
id: 1, title: 'Shared Paris Trip', description: 'Five days of pastry',
cover_image: 'https://cdn.example.com/a.jpg',
},
}));
expect(coverStyle()).toContain('https://cdn.example.com/a.jpg');
expect(screen.getByText('Five days of pastry')).toBeInTheDocument();
// Without start/end dates the date pill is skipped entirely.
expect(screen.queryByText(/days$/)).toBeNull();
});
it('keeps a root-relative cover path as-is', async () => {
await open('cover-abs-token', payload({
trip: { id: 1, title: 'Shared Paris Trip', cover_image: '/uploads/covers/b.jpg' },
}));
expect(coverStyle()).toContain('/uploads/covers/b.jpg');
expect(coverStyle()).not.toContain('/uploads//uploads/');
});
it('prefixes a bare filename with the uploads directory', async () => {
await open('cover-bare-token', payload({
trip: { id: 1, title: 'Shared Paris Trip', cover_image: 'c.jpg' },
}));
expect(coverStyle()).toContain('/uploads/c.jpg');
});
it('shows only the start date and no day count when the trip has no days', async () => {
await open('startonly-token', payload({
trip: { id: 1, title: 'Shared Paris Trip', start_date: '2026-07-01' },
}));
expect(
screen.getByText(fmtDate('2026-07-01T00:00:00Z', { day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' })),
).toBeInTheDocument();
expect(screen.queryByText(/^\d+ days$/)).toBeNull();
});
});
describe('FE-PAGE-SHARED-022: a payload without optional collections still renders', () => {
it('falls back to empty lists when places, reservations and permissions are missing', async () => {
await open('sparse-token', {
trip: { id: 1, title: 'Shared Paris Trip' },
days: [{ id: 1, trip_id: 1, day_number: 1, date: null, title: 'Lone day' }],
assignments: {},
dayNotes: {},
});
// share_map is undefined, so the Plan tab (the !== false branch) stays visible.
expect(screen.getByRole('button', { name: /plan/i })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /bookings/i })).toBeNull();
expect(screen.getByTestId('map-container')).toBeInTheDocument();
// The day card still renders even though reservations/accommodations are absent.
expect(screen.getByText('Lone day')).toBeInTheDocument();
expect(screen.getByText('0 places')).toBeInTheDocument();
expect(screen.getByText(/shared via/i)).toBeInTheDocument();
});
});
describe('FE-PAGE-SHARED-023: share_map=false hides the plan tab', () => {
it('lands on the first shared section instead of an empty map', async () => {
await open('nomap-token', payload({
permissions: { share_map: false, ...ALL_TABS },
packing: [{ id: 1, name: 'Passport', category: null, checked: false }],
reservations: [{ id: 1, title: 'Hotel Ibis', type: 'hotel', status: 'pending', metadata: null }],
}));
expect(screen.queryByRole('button', { name: /plan/i })).toBeNull();
// Bookings is the first shared section, so it is auto-selected and rendered.
await waitFor(() => expect(screen.getByText('Hotel Ibis')).toBeInTheDocument());
expect(screen.queryByTestId('map-container')).toBeNull();
});
});
describe('FE-PAGE-SHARED-024: day header details', () => {
it('renders an accommodation badge, the place count and the undated fallback', async () => {
const day = { id: 5, trip_id: 1, day_number: 1, date: null, title: null };
await open('accom-token', payload({
days: [day],
accommodations: [{ id: 3, place_name: 'Hotel Lutetia', start_day_id: 5, end_day_id: 5 }],
}));
expect(screen.getByText('Day 1')).toBeInTheDocument();
expect(screen.getByText('Hotel Lutetia')).toBeInTheDocument();
expect(screen.getByText('0 places')).toBeInTheDocument();
// No date row for an undated day.
expect(screen.queryByText(/2026/)).toBeNull();
});
it('sorts days by day_number regardless of payload order', async () => {
await open('order-token', payload({
days: [
{ id: 2, trip_id: 1, day_number: 2, date: null, title: 'Second' },
{ id: 1, trip_id: 1, day_number: 1, date: null, title: 'First' },
],
}));
const titles = Array.from(document.querySelectorAll('div')).map((d) => d.textContent);
expect(screen.getByText('First')).toBeInTheDocument();
expect(screen.getByText('Second')).toBeInTheDocument();
expect(titles.join('|').indexOf('First')).toBeLessThan(titles.join('|').lastIndexOf('Second'));
});
});
describe('FE-PAGE-SHARED-025: expanded day renders every place variant', () => {
const day = { id: 7, trip_id: 1, day_number: 1, date: '2026-07-01', title: 'Day One' };
const withImage = {
id: 201, name: 'Louvre', lat: 48.86, lng: 2.33, category_id: 4,
image_url: '/uploads/places/louvre.jpg', address: 'Rue de Rivoli', place_time: '09:00', end_time: '11:00',
};
const withDescription = {
id: 202, name: 'Seine Walk', lat: null, lng: null, category_id: null,
image_url: null, address: null, description: 'Along the river', place_time: '12:00', end_time: null,
};
const bare = { id: 203, name: 'Mystery Stop', lat: null, lng: null, category_id: 99, image_url: null };
it('shows the photo, the category colour, the address/description fallback and the time range', async () => {
await open('places-token', payload({
days: [day],
places: [withImage, withDescription, bare],
categories: [{ id: 4, name: 'Museum', color: '#ff0000', icon: 'landmark' }],
assignments: {
'7': [
{ id: 301, day_id: 7, place_id: 201, order_index: 0, place: withImage },
{ id: 302, day_id: 7, place_id: 202, order_index: 1, place: withDescription },
{ id: 303, day_id: 7, place_id: 203, order_index: 2, place: bare },
// A dangling assignment whose place was deleted must not crash the timeline.
{ id: 304, day_id: 7, place_id: 999, order_index: 3, place: null },
],
},
}));
// The count is the raw assignment count, including the one whose place is gone.
expect(screen.getByText('4 places')).toBeInTheDocument();
fireEvent.click(screen.getByText('Day One'));
await waitFor(() => expect(screen.getByText('Rue de Rivoli')).toBeInTheDocument());
expect((document.querySelector('img[src="/uploads/places/louvre.jpg"]') as HTMLImageElement)).toBeInTheDocument();
// A place with no address falls back to its description.
expect(screen.getByText('Along the river')).toBeInTheDocument();
// The bare place shows neither line and no time badge.
expect(screen.getByText('Mystery Stop')).toBeInTheDocument();
expect(screen.getByText(/09:00 – 11:00/)).toBeInTheDocument();
expect(screen.getByText(/^12:00$/)).toBeInTheDocument();
});
it('only maps the selected day and refits the map to it', async () => {
await open('mapday-token', payload({
days: [day],
places: [withImage, withDescription],
assignments: { '7': [{ id: 301, day_id: 7, place_id: 201, order_index: 0, place: withImage }] },
}));
// Unselected: both places are candidates, but only the geocoded one has a marker.
expect(screen.getAllByText('Louvre')).toHaveLength(1);
expect(screen.queryByText('Seine Walk')).toBeNull();
fireEvent.click(screen.getByText('Day One'));
await waitFor(() => expect(screen.getAllByText('Louvre')).toHaveLength(2));
// Collapsing again restores the trip-wide marker set.
fireEvent.click(screen.getByText('Day One'));
await waitFor(() => expect(screen.getAllByText('Louvre')).toHaveLength(1));
});
});
describe('FE-PAGE-SHARED-026: expanded day renders notes and single-leg transports', () => {
const day = { id: 9, trip_id: 1, day_number: 1, date: '2026-07-02', title: 'Day One' };
it('renders timed and untimed notes plus flight, train and fallback transport rows', async () => {
await open('transport-token', payload({
days: [day],
dayNotes: {
'9': [
{ id: 41, day_id: 9, text: 'Buy museum pass', time: '08:30', sort_order: 0 },
{ id: 42, day_id: 9, text: 'Anything goes', time: null, sort_order: 1 },
],
},
reservations: [
{
id: 51, title: 'Flight home', type: 'flight', status: 'confirmed', day_id: 9, end_day_id: 9,
reservation_time: '2026-07-02T18:00:00', reservation_end_time: '2026-07-02T20:30:00',
// Already-parsed metadata (not a JSON string) must work too.
metadata: { airline: 'Air France', flight_number: 'AF1', departure_airport: 'CDG', arrival_airport: 'TXL' },
},
{
id: 52, title: 'ICE 599', type: 'train', status: 'confirmed', day_id: 9, end_day_id: 9,
reservation_time: '2026-07-02T09:15:00', reservation_end_time: null,
metadata: JSON.stringify({ train_number: 'ICE 599', platform: '7' }),
},
{
id: 53, title: 'Harbour ferry', type: 'ferry', status: 'pending', day_id: 9, end_day_id: 9,
reservation_time: null, reservation_end_time: null, metadata: '',
},
],
}));
fireEvent.click(screen.getByText('Day One'));
await waitFor(() => expect(screen.getByText('Buy museum pass')).toBeInTheDocument());
expect(screen.getByText('08:30')).toBeInTheDocument();
expect(screen.getByText('Anything goes')).toBeInTheDocument();
expect(screen.getByText('Air France · AF1 · CDG → TXL')).toBeInTheDocument();
expect(screen.getByText(/Flight home · 18:00–20:30/)).toBeInTheDocument();
expect(screen.getByText('ICE 599 · Gl. 7')).toBeInTheDocument();
expect(screen.getByText(/^ICE 599 · 09:15$/)).toBeInTheDocument();
// An unmapped transport type falls back to the generic ticket row with no subtitle.
expect(screen.getByText('Harbour ferry')).toBeInTheDocument();
});
it('leaves the subtitle empty when the metadata carries no route at all', async () => {
await open('nometa-token', payload({
days: [day],
reservations: [
{
id: 61, title: 'Bus 100', type: 'bus', status: 'confirmed', day_id: 9, end_day_id: 9,
reservation_time: '2026-07-02T07:00:00', metadata: null,
},
{
id: 62, title: 'Regio', type: 'train', status: 'confirmed', day_id: 9, end_day_id: 9,
reservation_time: '2026-07-02T08:00:00', metadata: JSON.stringify({}),
},
{
id: 63, title: 'Shuttle', type: 'flight', status: 'confirmed', day_id: 9, end_day_id: 9,
reservation_time: '2026-07-02T10:00:00', metadata: JSON.stringify({ airline: 'KLM' }),
},
],
}));
fireEvent.click(screen.getByText('Day One'));
await waitFor(() => expect(screen.getByText(/Bus 100 · 07:00/)).toBeInTheDocument());
expect(screen.getByText(/Regio · 08:00/)).toBeInTheDocument();
// Only the airline is known, so no airport pair is appended.
expect(screen.getByText('KLM')).toBeInTheDocument();
});
it('renders each leg of a multi-leg train with its own train number and platform', async () => {
await open('trainlegs-token', payload({
days: [day],
reservations: [
{
id: 71, title: 'Rail to Milan', type: 'train', status: 'confirmed', day_id: 9, end_day_id: 9,
reservation_time: '2026-07-02T06:00:00', reservation_end_time: '2026-07-02T18:00:00',
metadata: JSON.stringify({
legs: [
{ from: 'Berlin', to: 'Basel', train_number: 'ICE 73', platform: '3', dep_day_id: 9, dep_time: '06:00', arr_day_id: 9, arr_time: '12:00' },
{ train_number: 'EC 51', dep_day_id: 9, dep_time: '12:30', arr_day_id: 9, arr_time: '18:00' },
],
}),
},
],
}));
fireEvent.click(screen.getByText('Day One'));
await waitFor(() => expect(screen.getByText('ICE 73 · Gl. 3 · Berlin → Basel')).toBeInTheDocument());
// The second leg has neither platform nor stations, so only its number shows.
expect(screen.getByText('EC 51')).toBeInTheDocument();
});
it('drops the route from a flight leg that has no airports of its own', async () => {
await open('flightlegs-token', payload({
days: [day],
reservations: [
{
id: 72, title: 'Long haul', type: 'flight', status: 'confirmed', day_id: 9, end_day_id: 9,
reservation_time: '2026-07-02T06:00:00', reservation_end_time: '2026-07-02T22:00:00',
metadata: JSON.stringify({
legs: [
{ from: 'FRA', to: 'DXB', airline: 'Emirates', flight_number: 'EK46', dep_day_id: 9, dep_time: '06:00', arr_day_id: 9, arr_time: '14:00' },
{ airline: 'Emirates', flight_number: 'EK350', dep_day_id: 9, dep_time: '16:00', arr_day_id: 9, arr_time: '22:00' },
],
}),
},
],
}));
fireEvent.click(screen.getByText('Day One'));
await waitFor(() => expect(screen.getByText('Emirates · EK46 · FRA → DXB')).toBeInTheDocument());
expect(screen.getByText('Emirates · EK350')).toBeInTheDocument();
});
});
describe('FE-PAGE-SHARED-027: bookings tab detail rows', () => {
it('shows date, time and location only when present and marks the status', async () => {
await open('bookingmeta-token', payload({
permissions: { share_bookings: true, share_packing: false, share_budget: false, share_collab: false },
reservations: [
{
id: 81, title: 'Museum entry', type: 'ticket', status: 'pending',
reservation_time: '2026-07-03T14:00:00', location: 'Louvre', metadata: '{}',
},
{
id: 82, title: 'Rental car', type: 'car', status: 'confirmed',
reservation_time: null, location: null, metadata: { airline: 'Sixt', flight_number: 'X9' },
},
{
id: 83, title: 'Night bus', type: 'bus', status: 'confirmed',
reservation_time: null, location: null, metadata: null,
},
{
id: 84, title: 'Coach', type: 'car', status: 'confirmed',
reservation_time: null, location: null, metadata: { airline: 'Flixbus' },
},
],
}));
fireEvent.click(screen.getByRole('button', { name: /bookings/i }));
await waitFor(() => expect(screen.getByText('Museum entry')).toBeInTheDocument());
expect(
screen.getByText(fmtDate('2026-07-03T00:00:00Z', { day: 'numeric', month: 'short', timeZone: 'UTC' })),
).toBeInTheDocument();
expect(screen.getByText('14:00')).toBeInTheDocument();
expect(screen.getByText('Louvre')).toBeInTheDocument();
expect(screen.getByText('Pending')).toBeInTheDocument();
// No date/time/location for the car — only the metadata airline line survives.
expect(screen.getByText('Sixt X9')).toBeInTheDocument();
expect(screen.getAllByText('Confirmed')).toHaveLength(3);
// Metadata-less bookings render the title only, no meta line.
expect(screen.getByText('Night bus')).toBeInTheDocument();
// An airline without a flight number appends nothing after it.
expect(screen.getByText('Flixbus')).toBeInTheDocument();
});
it('lists train legs with platform labels in the bookings tab', async () => {
await open('bookingtrain-token', payload({
permissions: { share_bookings: true, share_packing: false, share_budget: false, share_collab: false },
reservations: [
{
id: 91, title: 'Rail pass', type: 'train', status: 'confirmed',
reservation_time: '2026-07-04', metadata: JSON.stringify({
legs: [
{ from: 'Bern', to: 'Zurich', train_number: 'IC 8', platform: '12' },
{ train_number: 'S3' },
],
}),
},
],
}));
fireEvent.click(screen.getByRole('button', { name: /bookings/i }));
await waitFor(() => expect(screen.getByText('IC 8 Platform 12 Bern → Zurich')).toBeInTheDocument());
expect(screen.getByText('S3')).toBeInTheDocument();
// A bare date without a time renders the date chip only.
expect(
screen.getByText(fmtDate('2026-07-04T00:00:00Z', { day: 'numeric', month: 'short', timeZone: 'UTC' })),
).toBeInTheDocument();
});
it('omits the route of a flight leg without airports', async () => {
await open('bookingflight-token', payload({
permissions: { share_bookings: true, share_packing: false, share_budget: false, share_collab: false },
reservations: [
{
id: 92, title: 'Long haul', type: 'flight', status: 'confirmed', reservation_time: null,
metadata: JSON.stringify({
legs: [
{ from: 'FRA', to: 'DXB', airline: 'Emirates', flight_number: 'EK46' },
{ airline: 'Emirates', flight_number: 'EK350' },
],
}),
},
],
}));
fireEvent.click(screen.getByRole('button', { name: /bookings/i }));
await waitFor(() => expect(screen.getByText('Emirates EK46 FRA → DXB')).toBeInTheDocument());
expect(screen.getByText('Emirates EK350')).toBeInTheDocument();
});
it('renders no booking list at all when the trip has none', async () => {
await open('nobookings-token', payload({
permissions: { share_bookings: true, share_packing: false, share_budget: false, share_collab: false },
}));
fireEvent.click(screen.getByRole('button', { name: /bookings/i }));
expect(screen.queryByText('Confirmed')).toBeNull();
expect(screen.queryByTestId('map-container')).toBeNull();
});
});
describe('FE-PAGE-SHARED-028: packing list grouping', () => {
it('groups by category, falls back to Other and strikes through checked items', async () => {
await open('packinggroup-token', payload({
permissions: { share_bookings: false, share_packing: true, share_budget: false, share_collab: false },
packing: [
{ id: 1, name: 'Toothbrush', category: 'Bathroom', checked: true },
{ id: 2, name: 'Towel', category: 'Bathroom', checked: false },
{ id: 3, name: 'Charger', category: null, checked: false },
],
}));
fireEvent.click(screen.getByRole('button', { name: /packing/i }));
await waitFor(() => expect(screen.getByText('Bathroom')).toBeInTheDocument());
expect(screen.getByText('Other')).toBeInTheDocument();
expect(screen.getByText('Toothbrush')).toHaveStyle({ textDecoration: 'line-through' });
expect(screen.getByText('Towel')).toHaveStyle({ textDecoration: 'none' });
});
it('renders nothing when the packing list is empty', async () => {
await open('packingempty-token', payload({
permissions: { share_bookings: false, share_packing: true, share_budget: false, share_collab: false },
}));
fireEvent.click(screen.getByRole('button', { name: /packing/i }));
expect(screen.queryByText('Other')).toBeNull();
});
});
describe('FE-PAGE-SHARED-029: costs tab fallbacks', () => {
it('uses the trip currency for rows without one and dashes out priceless items', async () => {
server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([])));
await open('costfallback-token', payload({
trip: { id: 1, title: 'Shared Paris Trip', currency: 'GBP' },
permissions: { share_bookings: false, share_packing: false, share_budget: true, share_collab: false },
budget: [
{ id: 1, name: 'Hostel', total_price: '80', category: 'Stay', currency: null },
{ id: 2, name: 'Museum pass', total_price: null, category: null, currency: null },
],
}));
fireEvent.click(screen.getByRole('button', { name: /costs/i }));
await waitFor(() => expect(screen.getByText('Hostel')).toBeInTheDocument());
expect(screen.getByText('Stay')).toBeInTheDocument();
expect(screen.getByText('Other')).toBeInTheDocument();
expect(screen.getByText('—')).toBeInTheDocument();
// The priceless row contributes 0, so the total equals the single priced row.
expect(screen.getAllByText('80.00 GBP').length).toBeGreaterThanOrEqual(2);
});
it('falls back to the payload base currency and treats an unparsable price as zero', async () => {
server.use(http.get('https://api.frankfurter.dev/v2/rates', () => HttpResponse.json([])));
await open('costbase-token', payload({
// Neither the trip nor the rows name a currency, so curOf() lands on the base.
trip: { id: 1, title: 'Shared Paris Trip' },
baseCurrency: 'SEK',
permissions: { share_bookings: false, share_packing: false, share_budget: true, share_collab: false },
budget: [{ id: 1, name: 'Tips', total_price: 'free', category: 'Misc', currency: null }],
}));
fireEvent.click(screen.getByRole('button', { name: /costs/i }));
await waitFor(() => expect(screen.getByText('Tips')).toBeInTheDocument());
expect(screen.getAllByText('0.00 SEK').length).toBeGreaterThanOrEqual(3);
});
it('renders nothing when there are no expenses', async () => {
await open('costempty-token', payload({
permissions: { share_bookings: false, share_packing: false, share_budget: true, share_collab: false },
}));
fireEvent.click(screen.getByRole('button', { name: /costs/i }));
expect(screen.queryByText('Total Costs')).toBeNull();
});
});
describe('FE-PAGE-SHARED-030: chat tab message rendering', () => {
it('prints one date separator per day and falls back to an initial without an avatar', async () => {
await open('chatgroup-token', payload({
permissions: { share_bookings: false, share_packing: false, share_budget: false, share_collab: true },
collab: [
{ id: 1, username: 'alice', text: 'Morning', created_at: '2026-07-01T08:00:00Z', avatar: 'a.png' },
{ id: 2, username: 'bob', text: 'Afternoon', created_at: '2026-07-01T14:00:00Z', avatar: null },
{ id: 3, username: null, text: 'Next day', created_at: '2026-07-02T09:00:00Z', avatar: null },
],
}));
fireEvent.click(screen.getByRole('button', { name: /chat/i }));
await waitFor(() => expect(screen.getByText('Morning')).toBeInTheDocument());
expect(screen.getByText(/Chat · 3 messages/)).toBeInTheDocument();
// Two distinct days -> exactly one separator each, none for the second message
// of day one.
const sep = (iso: string) => fmtDate(iso, { weekday: 'short', day: 'numeric', month: 'short' });
expect(screen.getAllByText(sep('2026-07-01T08:00:00Z'))).toHaveLength(1);
expect(screen.getAllByText(sep('2026-07-02T09:00:00Z'))).toHaveLength(1);
expect(document.querySelector('img[src*="a.png"]')).toBeInTheDocument();
expect(screen.getByText('B')).toBeInTheDocument();
// A message without a username renders the "?" placeholder.
expect(screen.getByText('?')).toBeInTheDocument();
});
it('renders nothing when the chat is empty', async () => {
await open('chatempty-token', payload({
permissions: { share_bookings: false, share_packing: false, share_budget: false, share_collab: true },
}));
fireEvent.click(screen.getByRole('button', { name: /chat/i }));
expect(screen.queryByText(/messages/)).toBeNull();
});
});
describe('FE-PAGE-SHARED-031: language options highlight on hover', () => {
it('paints and clears the hover background of a language entry', async () => {
await open('langhover-token', payload());
fireEvent.click(screen.getByRole('button', { name: /english/i }));
const option = screen.getByRole('button', { name: /deutsch/i });
fireEvent.mouseEnter(option);
expect(option.style.background).toBe('rgb(243, 244, 246)');
fireEvent.mouseLeave(option);
expect(option.style.background).toBe('none');
});
});
});
File diff suppressed because it is too large Load Diff
+184
View File
@@ -0,0 +1,184 @@
// FE-PAGE-VCY-001 to FE-PAGE-VCY-007
// Sidebar wiring VacayPage.test.tsx leaves open: year stepping inside the list,
// the shared/school legend rows and the drawer / modal dismissals.
import React from 'react'
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { render, screen, fireEvent, waitFor, within } from '../../tests/helpers/render'
import { resetAllStores, seedStore } from '../../tests/helpers/store'
import { useVacayStore } from '../store/vacayStore'
import VacayPage from './VacayPage'
import type { VacayPlan, SharedVacayCalendar } from '../types'
vi.mock('../components/Vacay/VacayCalendar', () => ({ default: () => <div data-testid="calendar" /> }))
vi.mock('../components/Vacay/VacayPersons', () => ({ default: () => <div data-testid="persons" /> }))
vi.mock('../components/Vacay/VacayStats', () => ({ default: () => <div data-testid="stats" /> }))
vi.mock('../components/Vacay/VacaySharedCalendars', () => ({ default: () => <div data-testid="shared" /> }))
vi.mock('../components/Vacay/VacaySettings', () => ({ default: () => <div data-testid="settings" /> }))
vi.mock('../api/websocket', () => ({ addListener: vi.fn(), removeListener: vi.fn() }))
function baseState(over: Record<string, unknown> = {}): Record<string, unknown> {
return {
years: [2024, 2025, 2026],
selectedYear: 2025,
loading: false,
incomingInvites: [],
plan: null,
sharedCalendars: [],
loadAll: vi.fn(async () => {}),
loadPlan: vi.fn(async () => {}),
loadEntries: vi.fn(async () => {}),
loadStats: vi.fn(async () => {}),
loadHolidays: vi.fn(async () => {}),
loadShares: vi.fn(async () => {}),
loadSharedCalendars: vi.fn(async () => {}),
setSelectedYear: vi.fn((_y: number) => undefined),
addYear: vi.fn((_y: number) => undefined),
removeYear: vi.fn(async (_y: number) => {}),
...over,
}
}
function buildPlan(over: Partial<VacayPlan> = {}): VacayPlan {
return {
id: 1,
holidays_enabled: false,
school_holidays_enabled: false,
holidays_region: null,
holiday_calendars: [],
block_weekends: false,
carry_over_enabled: false,
company_holidays_enabled: false,
...over,
}
}
beforeEach(() => {
resetAllStores()
vi.clearAllMocks()
seedStore(useVacayStore, baseState())
})
/** Year card controls in DOM order: add-previous, prev, next, add-next. */
function yearCardButtons(): HTMLElement[] {
const card = screen.getByText('Year').closest('.vg-card') as HTMLElement
return within(card).getAllByRole('button')
}
describe('VacayPage sidebar', () => {
it('FE-PAGE-VCY-001: the year chevrons step inside the existing list', () => {
const setSelectedYear = vi.fn((_y: number) => undefined)
seedStore(useVacayStore, baseState({ setSelectedYear }))
render(<VacayPage />)
const [, prev, next] = yearCardButtons()
fireEvent.click(prev)
expect(setSelectedYear).toHaveBeenLastCalledWith(2024)
fireEvent.click(next)
expect(setSelectedYear).toHaveBeenLastCalledWith(2026)
})
it('FE-PAGE-VCY-002: the chevrons are disabled at the ends of the list', () => {
seedStore(useVacayStore, baseState({ years: [2025], selectedYear: 2025 }))
render(<VacayPage />)
const [, prev, next] = yearCardButtons()
expect(prev).toBeDisabled()
expect(next).toBeDisabled()
})
it('FE-PAGE-VCY-003: school-holiday calendars get their own legend swatch', async () => {
seedStore(useVacayStore, baseState({
plan: buildPlan({
holidays_enabled: true,
school_holidays_enabled: true,
holiday_calendars: [
{ id: 1, plan_id: 1, region: 'DE', label: 'Feiertage', color: '#fecaca', sort_order: 0 },
{ id: 2, plan_id: 1, region: 'NL', label: 'Schoolvakantie', color: '#bbf7d0', sort_order: 1, type: 'school_holiday' },
],
}),
}))
render(<VacayPage />)
await waitFor(() => expect(screen.getAllByText('Feiertage')[0]).toBeInTheDocument())
expect(screen.getAllByText('Schoolvakantie')[0]).toBeInTheDocument()
// The generic "Public Holiday" swatch only appears without a configured calendar.
expect(screen.queryByText('Public Holiday')).not.toBeInTheDocument()
})
it('FE-PAGE-VCY-004: a visible shared calendar adds the ring legend entry', async () => {
const sharedCalendars: SharedVacayCalendar[] = [
{ share_id: 1, owner_id: 3, owner_name: 'carol', color: '#f59e0b', hidden: false, entries: [], companyHolidays: [] },
]
seedStore(useVacayStore, baseState({ plan: buildPlan({ block_weekends: true }), sharedCalendars }))
render(<VacayPage />)
await waitFor(() => expect(screen.getAllByText('Shared (view only)')[0]).toBeInTheDocument())
expect(screen.getAllByText('Weekend')[0]).toBeInTheDocument()
})
it('FE-PAGE-VCY-005: hidden shared calendars leave the legend out entirely', () => {
const sharedCalendars: SharedVacayCalendar[] = [
{ share_id: 1, owner_id: 3, owner_name: 'carol', color: '#f59e0b', hidden: true, entries: [], companyHolidays: [] },
]
seedStore(useVacayStore, baseState({ plan: buildPlan(), sharedCalendars }))
render(<VacayPage />)
expect(screen.queryByText('Legend')).not.toBeInTheDocument()
})
it('FE-PAGE-VCY-006: the mobile drawer opens from the filter button and closes on the backdrop', async () => {
const { container } = render(<VacayPage />)
const toggle = [...container.querySelectorAll('button')].find(b => b.className.includes('lg:hidden')) as HTMLElement
fireEvent.click(toggle)
const backdrop = await waitFor(() => document.body.querySelector('.absolute.inset-0') as HTMLElement)
expect(screen.getAllByTestId('persons')).toHaveLength(2)
fireEvent.click(backdrop)
await waitFor(() => expect(screen.getAllByTestId('persons')).toHaveLength(1))
})
it('FE-PAGE-VCY-007: the settings modal closes through its own dismiss control', async () => {
render(<VacayPage />)
fireEvent.click(screen.getAllByRole('button', { name: /settings/i })[0])
expect(await screen.findByTestId('settings')).toBeInTheDocument()
const dialog = screen.getByTestId('settings').closest('div[class*="rounded"]') as HTMLElement
fireEvent.click(within(dialog.parentElement as HTMLElement).getAllByRole('button')[0])
await waitFor(() => expect(screen.queryByTestId('settings')).not.toBeInTheDocument())
})
it('FE-PAGE-VCY-007b: the compact header opens the settings modal too', async () => {
const { container } = render(<VacayPage />)
const header = container.querySelector('.lg\\:hidden.flex.items-center.justify-between') as HTMLElement
fireEvent.click(within(header).getAllByRole('button')[1])
expect(await screen.findByTestId('settings')).toBeInTheDocument()
})
it('FE-PAGE-VCY-008: the delete-year modal closes without removing the year', async () => {
const removeYear = vi.fn(async (_y: number) => {})
seedStore(useVacayStore, baseState({ removeYear }))
const { container } = render(<VacayPage />)
fireEvent.click(container.querySelector('.bg-red-500') as HTMLElement)
expect(await screen.findByText(/Remove 2024\?|Remove 2025\?|Remove 2026\?/)).toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
await waitFor(() => expect(screen.queryByRole('button', { name: 'Cancel' })).not.toBeInTheDocument())
expect(removeYear).not.toHaveBeenCalled()
})
it('FE-PAGE-VCY-009: Escape dismisses the delete-year modal as well', async () => {
const { container } = render(<VacayPage />)
fireEvent.click(container.querySelector('.bg-red-500') as HTMLElement)
expect(await screen.findByRole('button', { name: 'Cancel' })).toBeInTheDocument()
fireEvent.keyDown(document, { key: 'Escape' })
await waitFor(() => expect(screen.queryByRole('button', { name: 'Cancel' })).not.toBeInTheDocument())
})
})
@@ -0,0 +1,183 @@
// FE-ADMMTX-001 to FE-ADMMTX-011
import { http, HttpResponse } from 'msw';
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { buildAdminToast } from '../../../tests/helpers/mobileAdmin';
import { resetAllStores } from '../../../tests/helpers/store';
import { useTranslation } from '../../i18n';
import type { useToast } from '../../components/shared/Toast';
import AdminNotificationsPanel from './AdminNotificationsPanel';
type Spy = ReturnType<typeof vi.fn>;
function Harness({ toast }: { toast: Record<string, Spy> }) {
const { t } = useTranslation();
return <AdminNotificationsPanel t={t} toast={toast as unknown as ReturnType<typeof useToast>} />;
}
function renderPanel() {
const toast = buildAdminToast();
render(<Harness toast={toast} />);
return toast;
}
function matrix(overrides: Record<string, unknown> = {}) {
return {
event_types: ['version_available'],
channels: [
{ id: 'inapp', source: 'builtin', active: true, configured: true },
{ id: 'email', source: 'builtin', active: true, configured: true },
{ id: 'webhook', source: 'builtin', active: false, configured: false },
],
implemented_combos: { version_available: ['inapp', 'email'] },
preferences: { version_available: { inapp: true, email: false } },
...overrides,
};
}
function servePreferences(data: Record<string, unknown>) {
server.use(http.get('/api/admin/notification-preferences', () => HttpResponse.json(data)));
}
beforeEach(() => {
resetAllStores();
});
afterEach(() => {
server.resetHandlers();
});
describe('AdminNotificationsPanel', () => {
it('FE-ADMMTX-001: shows a loading line until the matrix arrives', () => {
servePreferences(matrix());
renderPanel();
expect(screen.getByText('Loading…')).toBeInTheDocument();
});
it('FE-ADMMTX-002: stays on the loading line when the request fails', async () => {
server.use(http.get('/api/admin/notification-preferences', () => HttpResponse.json({}, { status: 500 })));
renderPanel();
await waitFor(() => expect(screen.getByText('Loading…')).toBeInTheDocument());
});
it('FE-ADMMTX-003: renders the empty state when no event types exist', async () => {
servePreferences(matrix({ event_types: [], implemented_combos: {}, preferences: {} }));
renderPanel();
expect(await screen.findByText(/no notification channels/i)).toBeInTheDocument();
});
it('FE-ADMMTX-004: renders one column per active, implemented channel', async () => {
servePreferences(matrix());
renderPanel();
expect(await screen.findByText('In-App')).toBeInTheDocument();
expect(screen.getByText('Email')).toBeInTheDocument();
// webhook is inactive server-side → no column
expect(screen.queryByText('Webhook')).not.toBeInTheDocument();
});
it('FE-ADMMTX-005: renders the translated event label as the row header', async () => {
servePreferences(matrix());
renderPanel();
expect(await screen.findByText('New version available')).toBeInTheDocument();
});
it('FE-ADMMTX-006: falls back to the raw event id for unknown events', async () => {
servePreferences(
matrix({
event_types: ['custom.event'],
implemented_combos: { 'custom.event': ['email'] },
preferences: { 'custom.event': { email: true } },
})
);
renderPanel();
expect(await screen.findByText('custom.event')).toBeInTheDocument();
});
it('FE-ADMMTX-007: renders a dash where a channel is not implemented for an event', async () => {
servePreferences(
matrix({
event_types: ['version_available', 'custom.event'],
implemented_combos: { version_available: ['inapp', 'email'], 'custom.event': ['email'] },
})
);
renderPanel();
await screen.findByText('New version available');
// custom.event has no in-app implementation → placeholder instead of a toggle
expect(screen.getByText('—')).toBeInTheDocument();
});
it('FE-ADMMTX-008: toggling a preference PUTs the whole matrix', async () => {
let body: Record<string, unknown> | null = null;
servePreferences(matrix());
server.use(
http.put('/api/admin/notification-preferences', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ success: true });
})
);
renderPanel();
await screen.findByText('New version available');
const toggles = screen.getAllByRole('button');
fireEvent.click(toggles[1]); // email column, currently off
await waitFor(() => expect(body).toEqual({ version_available: { inapp: true, email: true } }));
});
it('FE-ADMMTX-009: an unknown preference defaults to on and toggles off', async () => {
let body: Record<string, unknown> | null = null;
servePreferences(matrix({ preferences: {} }));
server.use(
http.put('/api/admin/notification-preferences', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ success: true });
})
);
renderPanel();
await screen.findByText('New version available');
fireEvent.click(screen.getAllByRole('button')[0]);
await waitFor(() => expect(body).toEqual({ version_available: { inapp: false } }));
});
it('FE-ADMMTX-010: a failing save reverts the toggle and toasts', async () => {
servePreferences(matrix());
server.use(
http.put('/api/admin/notification-preferences', () => HttpResponse.json({}, { status: 500 }))
);
const toast = renderPanel();
await screen.findByText('New version available');
const emailToggle = screen.getAllByRole('button')[1];
fireEvent.click(emailToggle);
await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Error'));
expect(emailToggle.className).toContain('bg-edge');
});
it('FE-ADMMTX-011: a channel that no event implements gets no column', async () => {
servePreferences(
matrix({
channels: [
{ id: 'inapp', source: 'builtin', active: true, configured: true },
{ id: 'ntfy', source: 'builtin', active: true, configured: true },
],
implemented_combos: { version_available: ['inapp'] },
})
);
renderPanel();
expect(await screen.findByText('In-App')).toBeInTheDocument();
expect(screen.queryByText('Ntfy')).not.toBeInTheDocument();
});
});
@@ -0,0 +1,542 @@
// FE-ADMNOT-001 to FE-ADMNOT-041
import { http, HttpResponse } from 'msw';
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { fireEvent, render, screen, waitFor, within } from '../../../tests/helpers/render';
import { buildAdminHook, type AdminHook } from '../../../tests/helpers/mobileAdmin';
import { resetAllStores } from '../../../tests/helpers/store';
import { useTranslation } from '../../i18n';
import AdminNotificationsTab from './AdminNotificationsTab';
vi.mock('./AdminNotificationsPanel', () => ({
default: () => <div data-testid="admin-notifications-panel" />,
}));
type Spy = ReturnType<typeof vi.fn>;
type Spies = Record<string, Spy> & { toast: Record<string, Spy> };
type SmtpValues = Record<string, string>;
function Harness({ admin }: { admin: AdminHook }) {
const { t } = useTranslation();
return <AdminNotificationsTab admin={admin} t={t} />;
}
function renderTab(overrides: Record<string, unknown> = {}) {
const admin = buildAdminHook(overrides);
render(<Harness admin={admin} />);
return admin as unknown as Spies;
}
/**
* setSmtpValues is always called with a functional updater; replaying it against
* the fixture's own values is the only way to see what the click intended.
*/
function replaySmtp(spy: Spy, callIndex: number, base: SmtpValues = {}): SmtpValues {
const updater = spy.mock.calls[callIndex][0] as (prev: SmtpValues) => SmtpValues;
return updater(base);
}
/** The card element whose <h2> matches the given heading text. */
function card(heading: string | RegExp): HTMLElement {
return screen.getByRole('heading', { name: heading }).closest<HTMLElement>('.rounded-xl')!;
}
const EMAIL_ON: SmtpValues = { notification_channels: 'email', smtp_host: 'mail.example.com' };
/**
* The text inputs hand setSmtpValues an updater that reads e.target.value lazily,
* so a spy call can no longer be replayed once React re-rendered the controlled
* input. This harness keeps the values in real state instead.
*/
function StatefulHarness({ initial }: { initial: SmtpValues }) {
const { t } = useTranslation();
const [smtpValues, setSmtpValues] = React.useState<SmtpValues>(initial);
const admin = buildAdminHook({ smtpValues, setSmtpValues });
return <AdminNotificationsTab admin={admin} t={t} />;
}
beforeEach(() => {
resetAllStores();
});
afterEach(() => {
server.resetHandlers();
});
describe('AdminNotificationsTab', () => {
it('FE-ADMNOT-001: renders every channel panel plus the preference matrix', () => {
renderTab();
expect(screen.getByRole('heading', { name: 'Email (SMTP)' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: /^webhook$/i })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Ntfy' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'In-App' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Trip Reminders' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Admin Webhook' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Admin Ntfy' })).toBeInTheDocument();
expect(screen.getByTestId('admin-notifications-panel')).toBeInTheDocument();
});
it('FE-ADMNOT-002: hides the SMTP fields until smtpLoaded is true', () => {
renderTab({ smtpLoaded: false });
expect(screen.queryByPlaceholderText('mail.example.com')).not.toBeInTheDocument();
expect(screen.queryByPlaceholderText('https://discord.com/api/webhooks/...')).not.toBeInTheDocument();
expect(screen.queryByPlaceholderText('https://ntfy.sh')).not.toBeInTheDocument();
});
it('FE-ADMNOT-003: renders all five SMTP fields once loaded', () => {
renderTab({ smtpValues: EMAIL_ON });
expect(screen.getByPlaceholderText('mail.example.com')).toHaveValue('mail.example.com');
expect(screen.getByPlaceholderText('587')).toBeInTheDocument();
expect(screen.getAllByPlaceholderText('trek@example.com')).toHaveLength(2);
expect(screen.getByPlaceholderText('••••••••')).toBeInTheDocument();
});
it('FE-ADMNOT-004: greys out the SMTP body while the email channel is off', () => {
renderTab({ smtpValues: { notification_channels: 'none' } });
const body = screen.getByPlaceholderText('mail.example.com').closest<HTMLElement>('.p-6')!;
expect(body.className).toContain('pointer-events-none');
});
it('FE-ADMNOT-005: enabling the email channel PUTs the merged channel list', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
const admin = renderTab({ smtpValues: { notification_channels: 'webhook' } });
fireEvent.click(within(card('Email (SMTP)')).getAllByRole('button')[0]);
await waitFor(() => expect(body).toEqual({ notification_channels: 'email,webhook' }));
expect(replaySmtp(admin.setSmtpValues, 0).notification_channels).toBe('email,webhook');
});
it('FE-ADMNOT-006: disabling the last channel falls back to "none"', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
renderTab({ smtpValues: { notification_channels: 'email' } });
fireEvent.click(within(card('Email (SMTP)')).getAllByRole('button')[0]);
await waitFor(() => expect(body).toEqual({ notification_channels: 'none' }));
});
it('FE-ADMNOT-007: unknown channel ids survive a toggle instead of being dropped', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
renderTab({ smtpValues: { notification_channels: 'email, plugin-gotify' } });
fireEvent.click(within(card('Ntfy')).getAllByRole('button')[0]);
await waitFor(() => expect(body).toEqual({ notification_channels: 'email,ntfy,plugin-gotify' }));
});
it('FE-ADMNOT-008: a failing channel toggle reverts and toasts', async () => {
server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ smtpValues: { notification_channels: 'email' } });
fireEvent.click(within(card(/^webhook$/i)).getAllByRole('button')[0]);
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
expect(replaySmtp(admin.setSmtpValues, 0).notification_channels).toBe('email,webhook');
expect(replaySmtp(admin.setSmtpValues, 1).notification_channels).toBe('email');
});
it('FE-ADMNOT-009: falls back to the legacy singular notification_channel key', () => {
renderTab({ smtpValues: { notification_channel: 'email', smtp_host: 'mail.example.com' } });
const body = screen.getByPlaceholderText('mail.example.com').closest<HTMLElement>('.p-6')!;
expect(body.className).not.toContain('pointer-events-none');
});
it('FE-ADMNOT-010: typing in an SMTP field writes that key back', () => {
render(<StatefulHarness initial={EMAIL_ON} />);
fireEvent.change(screen.getByPlaceholderText('587'), { target: { value: '465' } });
fireEvent.change(screen.getByPlaceholderText('mail.example.com'), { target: { value: 'smtp.test' } });
expect(screen.getByPlaceholderText('587')).toHaveValue('465');
expect(screen.getByPlaceholderText('mail.example.com')).toHaveValue('smtp.test');
});
it('FE-ADMNOT-011: the TLS toggle flips smtp_skip_tls_verify', () => {
const admin = renderTab({ smtpValues: { ...EMAIL_ON, smtp_skip_tls_verify: 'false' } });
const tlsRow = screen.getByText('Skip TLS certificate check').closest<HTMLElement>('div[style]')!;
fireEvent.click(within(tlsRow).getByRole('button'));
expect(replaySmtp(admin.setSmtpValues, 0).smtp_skip_tls_verify).toBe('true');
});
it('FE-ADMNOT-012: the TLS toggle flips back when already enabled', () => {
const admin = renderTab({ smtpValues: { ...EMAIL_ON, smtp_skip_tls_verify: 'true' } });
const tlsRow = screen.getByText('Skip TLS certificate check').closest<HTMLElement>('div[style]')!;
fireEvent.click(within(tlsRow).getByRole('button'));
expect(replaySmtp(admin.setSmtpValues, 0).smtp_skip_tls_verify).toBe('false');
});
it('FE-ADMNOT-013: saving SMTP sends only the credential keys that are set', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
}),
http.get('/api/auth/app-config', () => HttpResponse.json({ trip_reminders_enabled: true }))
);
const admin = renderTab({
smtpValues: { ...EMAIL_ON, smtp_port: '587', notification_channels: 'email', admin_ntfy_topic: 'x' },
});
fireEvent.click(within(card('Email (SMTP)')).getByRole('button', { name: /^save$/i }));
await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('Notification settings saved'));
expect(body).toEqual({ smtp_host: 'mail.example.com', smtp_port: '587' });
await waitFor(() => expect(admin.setTripRemindersEnabled).toHaveBeenCalledWith(true));
});
it('FE-ADMNOT-014: a failing SMTP save toasts the generic error', async () => {
server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ smtpValues: EMAIL_ON });
fireEvent.click(within(card('Email (SMTP)')).getByRole('button', { name: /^save$/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
});
it('FE-ADMNOT-015: the test-email button needs a configured SMTP host', () => {
renderTab({ smtpValues: { notification_channels: 'email' } });
expect(screen.getByRole('button', { name: /send test email/i })).toBeDisabled();
});
it('FE-ADMNOT-016: a successful SMTP test toasts success', async () => {
server.use(http.post('/api/notifications/test-smtp', () => HttpResponse.json({ success: true })));
const admin = renderTab({ smtpValues: EMAIL_ON });
fireEvent.click(screen.getByRole('button', { name: /send test email/i }));
await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('Test email sent successfully'));
});
it('FE-ADMNOT-017: a rejected SMTP test surfaces the server error', async () => {
server.use(
http.post('/api/notifications/test-smtp', () => HttpResponse.json({ success: false, error: 'auth failed' }))
);
const admin = renderTab({ smtpValues: EMAIL_ON });
fireEvent.click(screen.getByRole('button', { name: /send test email/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('auth failed'));
});
it('FE-ADMNOT-018: a failing SMTP test request toasts the fallback message', async () => {
server.use(http.post('/api/notifications/test-smtp', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ smtpValues: EMAIL_ON });
fireEvent.click(screen.getByRole('button', { name: /send test email/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Test email failed'));
});
it('FE-ADMNOT-019: enabling trip reminders PUTs true and refreshes the store flag', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
}),
http.get('/api/auth/app-config', () => HttpResponse.json({ trip_reminders_enabled: false }))
);
const admin = renderTab({ smtpValues: { notify_trip_reminder: 'false' } });
fireEvent.click(within(card('Trip Reminders')).getByRole('button'));
await waitFor(() => expect(body).toEqual({ notify_trip_reminder: 'true' }));
expect(admin.toast.success).toHaveBeenCalledWith('Trip reminders enabled');
await waitFor(() => expect(admin.setTripRemindersEnabled).toHaveBeenCalledWith(false));
});
it('FE-ADMNOT-020: disabling trip reminders toasts the disabled message', async () => {
server.use(http.get('/api/auth/app-config', () => HttpResponse.json({})));
const admin = renderTab({ smtpValues: {} });
fireEvent.click(within(card('Trip Reminders')).getByRole('button'));
await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('Trip reminders disabled'));
expect(replaySmtp(admin.setSmtpValues, 0).notify_trip_reminder).toBe('false');
});
it('FE-ADMNOT-021: a failing trip-reminder toggle reverts the value', async () => {
server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ smtpValues: {} });
fireEvent.click(within(card('Trip Reminders')).getByRole('button'));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
expect(replaySmtp(admin.setSmtpValues, 1).notify_trip_reminder).toBe('true');
});
it('FE-ADMNOT-022: the admin webhook URL is editable and saved', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
const admin = renderTab({ smtpValues: { admin_webhook_url: 'https://hooks.example/1' } });
fireEvent.click(within(card('Admin Webhook')).getByRole('button', { name: /^save$/i }));
await waitFor(() => expect(body).toEqual({ admin_webhook_url: 'https://hooks.example/1' }));
expect(admin.toast.success).toHaveBeenCalledWith('Admin webhook URL saved');
});
it('FE-ADMNOT-023: the admin webhook URL input is editable', () => {
render(<StatefulHarness initial={{ admin_webhook_url: 'https://hooks.example/1' }} />);
const input = screen.getByPlaceholderText('https://discord.com/api/webhooks/...');
fireEvent.change(input, { target: { value: 'https://hooks.example/2' } });
expect(input).toHaveValue('https://hooks.example/2');
});
it('FE-ADMNOT-024: a stored webhook URL renders masked with an empty input', () => {
renderTab({ smtpValues: { admin_webhook_url: '••••••••' } });
const input = within(card('Admin Webhook')).getByPlaceholderText('••••••••');
expect(input).toHaveValue('');
});
it('FE-ADMNOT-025: a failing admin-webhook save toasts the generic error', async () => {
server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ smtpValues: { admin_webhook_url: 'https://hooks.example/1' } });
fireEvent.click(within(card('Admin Webhook')).getByRole('button', { name: /^save$/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
});
it('FE-ADMNOT-026: the webhook test button is disabled without a URL', () => {
renderTab({ smtpValues: {} });
expect(screen.getByRole('button', { name: /send test webhook/i })).toBeDisabled();
});
it('FE-ADMNOT-027: a successful webhook test posts the URL and toasts', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.post('/api/notifications/test-webhook', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ success: true });
})
);
const admin = renderTab({ smtpValues: { admin_webhook_url: 'https://hooks.example/1' } });
fireEvent.click(screen.getByRole('button', { name: /send test webhook/i }));
await waitFor(() => expect(body).toEqual({ url: 'https://hooks.example/1' }));
expect(admin.toast.success).toHaveBeenCalledWith('Test webhook sent successfully');
});
it('FE-ADMNOT-028: a rejected webhook test surfaces the server error', async () => {
server.use(
http.post('/api/notifications/test-webhook', () => HttpResponse.json({ success: false, error: '404 from hook' }))
);
const admin = renderTab({ smtpValues: { admin_webhook_url: 'https://hooks.example/1' } });
fireEvent.click(screen.getByRole('button', { name: /send test webhook/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('404 from hook'));
});
it('FE-ADMNOT-029: testing a masked webhook URL skips the pre-save', async () => {
let putCalls = 0;
server.use(
http.put('/api/auth/app-settings', () => {
putCalls += 1;
return HttpResponse.json({});
}),
http.post('/api/notifications/test-webhook', () => HttpResponse.json({ success: true }))
);
const admin = renderTab({ smtpValues: { admin_webhook_url: '••••••••' } });
fireEvent.click(screen.getByRole('button', { name: /send test webhook/i }));
await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('Test webhook sent successfully'));
expect(putCalls).toBe(0);
});
it('FE-ADMNOT-030: ntfy server, topic and token inputs write back', () => {
render(<StatefulHarness initial={{}} />);
const server_ = screen.getByPlaceholderText('https://ntfy.sh');
fireEvent.change(server_, { target: { value: 'https://ntfy.example' } });
const topic = screen.getByPlaceholderText('trek-admin-alerts');
fireEvent.change(topic, { target: { value: 'alerts' } });
const token = screen.getByText('Access Token (optional)').parentElement!.querySelector('input')!;
fireEvent.change(token, { target: { value: 'tk_123' } });
expect(server_).toHaveValue('https://ntfy.example');
expect(topic).toHaveValue('alerts');
expect(token).toHaveValue('tk_123');
});
it('FE-ADMNOT-031: clearing a stored ntfy token PUTs an empty value', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
const admin = renderTab({ smtpValues: { admin_ntfy_token: '••••••••' } });
fireEvent.click(screen.getByRole('button', { name: /^clear$/i }));
await waitFor(() => expect(body).toEqual({ admin_ntfy_token: '' }));
expect(admin.toast.success).toHaveBeenCalledWith('Admin access token cleared');
expect(replaySmtp(admin.setSmtpValues, 0).admin_ntfy_token).toBe('');
});
it('FE-ADMNOT-032: the clear button only exists for a stored token', () => {
renderTab({ smtpValues: { admin_ntfy_token: 'plain' } });
expect(screen.queryByRole('button', { name: /^clear$/i })).not.toBeInTheDocument();
});
it('FE-ADMNOT-033: saving admin ntfy omits a masked token', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
const admin = renderTab({
smtpValues: { admin_ntfy_server: 'https://ntfy.example', admin_ntfy_topic: 'alerts', admin_ntfy_token: '••••••••' },
});
fireEvent.click(within(card('Admin Ntfy')).getByRole('button', { name: /^save$/i }));
await waitFor(() =>
expect(body).toEqual({ admin_ntfy_server: 'https://ntfy.example', admin_ntfy_topic: 'alerts' })
);
expect(admin.toast.success).toHaveBeenCalledWith('Admin ntfy settings saved');
});
it('FE-ADMNOT-034: saving admin ntfy includes a freshly typed token', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
renderTab({ smtpValues: { admin_ntfy_topic: 'alerts', admin_ntfy_token: 'tk_live' } });
fireEvent.click(within(card('Admin Ntfy')).getByRole('button', { name: /^save$/i }));
await waitFor(() => expect(body).toMatchObject({ admin_ntfy_token: 'tk_live' }));
});
it('FE-ADMNOT-035: a failing admin-ntfy save toasts the generic error', async () => {
server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ smtpValues: { admin_ntfy_topic: 'alerts' } });
fireEvent.click(within(card('Admin Ntfy')).getByRole('button', { name: /^save$/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
});
it('FE-ADMNOT-036: the ntfy test button is disabled without a topic', () => {
renderTab({ smtpValues: {} });
expect(within(card('Admin Ntfy')).getByRole('button', { name: /send test ntfy/i })).toBeDisabled();
});
it('FE-ADMNOT-037: a successful ntfy test posts topic, server and token', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.post('/api/notifications/test-ntfy', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ success: true });
})
);
const admin = renderTab({
smtpValues: { admin_ntfy_topic: ' alerts ', admin_ntfy_server: 'https://ntfy.example', admin_ntfy_token: 'tk' },
});
fireEvent.click(within(card('Admin Ntfy')).getByRole('button', { name: /send test ntfy/i }));
await waitFor(() =>
expect(body).toEqual({ topic: 'alerts', server: 'https://ntfy.example', token: 'tk' })
);
expect(admin.toast.success).toHaveBeenCalledWith('Test ntfy sent successfully');
});
it('FE-ADMNOT-038: a masked ntfy token is sent as null', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.post('/api/notifications/test-ntfy', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ success: false, error: 'topic rejected' });
})
);
const admin = renderTab({ smtpValues: { admin_ntfy_topic: 'alerts', admin_ntfy_token: '••••••••' } });
fireEvent.click(within(card('Admin Ntfy')).getByRole('button', { name: /send test ntfy/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('topic rejected'));
expect(body).toEqual({ topic: 'alerts', server: null, token: null });
});
it('FE-ADMNOT-039: a failing ntfy test request toasts the fallback message', async () => {
server.use(http.post('/api/notifications/test-ntfy', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ smtpValues: { admin_ntfy_topic: 'alerts' } });
fireEvent.click(within(card('Admin Ntfy')).getByRole('button', { name: /send test ntfy/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Test ntfy failed'));
});
it('FE-ADMNOT-040: a failing webhook test request toasts the fallback message', async () => {
server.use(http.post('/api/notifications/test-webhook', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ smtpValues: { admin_webhook_url: 'https://hooks.example/1' } });
fireEvent.click(screen.getByRole('button', { name: /send test webhook/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Test webhook failed'));
});
it('FE-ADMNOT-041: a failing token clear toasts the generic error', async () => {
server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ smtpValues: { admin_ntfy_token: '••••••••' } });
fireEvent.click(screen.getByRole('button', { name: /^clear$/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
});
});
@@ -0,0 +1,471 @@
// FE-ADMSET-001 to FE-ADMSET-040
import { http, HttpResponse } from 'msw';
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { fireEvent, render, screen, waitFor, within } from '../../../tests/helpers/render';
import { buildAdminHook, type AdminHook } from '../../../tests/helpers/mobileAdmin';
import { resetAllStores } from '../../../tests/helpers/store';
import { useTranslation } from '../../i18n';
import type { OidcConfig } from './adminModel';
import AdminSettingsTab from './AdminSettingsTab';
type Spy = ReturnType<typeof vi.fn>;
type Spies = Record<string, Spy> & { toast: Record<string, Spy> };
function Harness({ admin }: { admin: AdminHook }) {
const { t } = useTranslation();
return <AdminSettingsTab admin={admin} t={t} />;
}
function renderTab(overrides: Record<string, unknown> = {}) {
const admin = buildAdminHook(overrides);
render(<Harness admin={admin} />);
return admin as unknown as Spies;
}
/** The card element whose <h2> matches the given heading text. */
function card(heading: string | RegExp): HTMLElement {
return screen.getByRole('heading', { name: heading }).closest<HTMLElement>('.rounded-xl')!;
}
/** The toggle button in the row belonging to a label paragraph. */
function toggleFor(label: string): HTMLElement {
const row = screen.getAllByText(label).map(el => el.closest<HTMLElement>('.flex.items-center.justify-between'));
const found = row.find(Boolean)!;
return within(found).getByRole('button');
}
const EMPTY_OIDC: OidcConfig = {
issuer: '',
client_id: '',
client_secret: '',
client_secret_set: false,
display_name: '',
discovery_url: '',
};
/**
* setOidcConfig gets an updater that reads e.target.value lazily, so a spy call
* can no longer be replayed once React has re-rendered the controlled input.
* This harness keeps the config in real state instead.
*/
function OidcHarness() {
const { t } = useTranslation();
const [oidcConfig, setOidcConfig] = React.useState<OidcConfig>(EMPTY_OIDC);
const admin = buildAdminHook({ oidcConfig, setOidcConfig });
return <AdminSettingsTab admin={admin} t={t} />;
}
beforeEach(() => {
resetAllStores();
});
afterEach(() => {
server.resetHandlers();
});
describe('AdminSettingsTab', () => {
it('FE-ADMSET-001: renders every settings card', () => {
renderTab();
expect(screen.getByRole('heading', { name: 'Authentication Methods' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Passkey login' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: /require two-factor/i })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Allowed File Types' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'API Keys' })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: /single sign-on/i })).toBeInTheDocument();
expect(screen.getByRole('heading', { name: /danger zone/i })).toBeInTheDocument();
});
it('FE-ADMSET-002: hides the env-override hint unless OIDC_ONLY is set', () => {
renderTab();
expect(screen.queryByText(/OIDC_ONLY environment variable/i)).not.toBeInTheDocument();
expect(toggleFor('Password Login')).not.toBeDisabled();
});
it('FE-ADMSET-003: shows the env-override hint and disables the password toggles', () => {
renderTab({ envOverrideOidcOnly: true });
expect(screen.getByText(/OIDC_ONLY environment variable/i)).toBeInTheDocument();
expect(toggleFor('Password Login')).toBeDisabled();
expect(toggleFor('Password Registration')).toBeDisabled();
});
it('FE-ADMSET-004: password login toggle sends the inverted value', () => {
const admin = renderTab({ passwordLogin: true, oidcLogin: true });
fireEvent.click(toggleFor('Password Login'));
expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith('password_login', false, admin.setPasswordLogin);
});
it('FE-ADMSET-005: password login toggle is locked out when it is the last method', () => {
renderTab({ passwordLogin: false, oidcLogin: false });
const toggle = toggleFor('Password Login');
expect(toggle).toBeDisabled();
expect(toggle).toHaveAttribute('title', 'At least one login method must remain enabled');
});
it('FE-ADMSET-006: password registration toggle sends the inverted value', () => {
const admin = renderTab({ passwordRegistration: false });
fireEvent.click(toggleFor('Password Registration'));
expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith(
'password_registration',
true,
admin.setPasswordRegistration
);
});
it('FE-ADMSET-007: SSO rows are hidden until OIDC is configured', () => {
renderTab({ oidcConfigured: false });
expect(screen.queryByText('SSO Login')).not.toBeInTheDocument();
expect(screen.queryByText('SSO Auto-Provisioning')).not.toBeInTheDocument();
});
it('FE-ADMSET-008: SSO login toggle sends the inverted value', () => {
const admin = renderTab({ oidcConfigured: true, oidcLogin: true, passwordLogin: true });
fireEvent.click(toggleFor('SSO Login'));
expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith('oidc_login', false, admin.setOidcLogin);
});
it('FE-ADMSET-009: SSO login toggle is disabled when password login is already off', () => {
renderTab({ oidcConfigured: true, oidcLogin: true, passwordLogin: false });
expect(toggleFor('SSO Login')).toBeDisabled();
});
it('FE-ADMSET-010: SSO auto-provisioning toggle sends the inverted value', () => {
const admin = renderTab({ oidcConfigured: true, oidcRegistration: false });
fireEvent.click(toggleFor('SSO Auto-Provisioning'));
expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith('oidc_registration', true, admin.setOidcRegistration);
});
it('FE-ADMSET-011: passkey toggle sends the inverted value', () => {
const admin = renderTab({ passkeyLogin: false });
fireEvent.click(toggleFor('Enable passkey login'));
expect(admin.handleToggleAuthSetting).toHaveBeenCalledWith('passkey_login', true, admin.setPasskeyLogin);
});
it('FE-ADMSET-012: warns only when passkey login is on but no RP ID resolves', () => {
const { unmount } = render(<Harness admin={buildAdminHook({ passkeyLogin: true, passkeyConfigured: false })} />);
expect(screen.getByText(/No WebAuthn domain resolves/)).toBeInTheDocument();
unmount();
render(<Harness admin={buildAdminHook({ passkeyLogin: true, passkeyConfigured: true })} />);
expect(screen.queryByText(/No WebAuthn domain resolves/)).not.toBeInTheDocument();
});
it('FE-ADMSET-013: webauthn RP ID and origins inputs write through their setters', () => {
const admin = renderTab({ webauthnRpId: 'old.example', webauthnOrigins: '' });
expect(screen.getByPlaceholderText('trek.example.org')).toHaveValue('old.example');
fireEvent.change(screen.getByPlaceholderText('trek.example.org'), { target: { value: 'trek.test' } });
expect(admin.setWebauthnRpId).toHaveBeenCalledWith('trek.test');
fireEvent.change(screen.getByPlaceholderText('https://trek.example.org'), {
target: { value: 'https://trek.test' },
});
expect(admin.setWebauthnOrigins).toHaveBeenCalledWith('https://trek.test');
});
it('FE-ADMSET-014: passkey save button calls handleSaveWebauthn', () => {
const admin = renderTab();
fireEvent.click(within(card('Passkey login')).getByRole('button', { name: /save/i }));
expect(admin.handleSaveWebauthn).toHaveBeenCalledTimes(1);
});
it('FE-ADMSET-015: the passkey save button is disabled while saving', () => {
renderTab({ savingWebauthn: true });
expect(within(card('Passkey login')).getByRole('button', { name: /save/i })).toBeDisabled();
});
it('FE-ADMSET-016: require-MFA toggle flips the current value', () => {
const admin = renderTab({ requireMfa: false });
fireEvent.click(within(card(/require two-factor/i)).getByRole('button'));
expect(admin.handleToggleRequireMfa).toHaveBeenCalledWith(true);
});
it('FE-ADMSET-017: file types input writes through its setter', () => {
const admin = renderTab({ allowedFileTypes: 'jpg,png' });
fireEvent.change(screen.getByDisplayValue('jpg,png'), { target: { value: 'jpg,png,pdf' } });
expect(admin.setAllowedFileTypes).toHaveBeenCalledWith('jpg,png,pdf');
});
it('FE-ADMSET-018: saving file types PUTs allowed_file_types and toasts', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
const admin = renderTab({ allowedFileTypes: 'jpg,png' });
fireEvent.click(within(card('Allowed File Types')).getByRole('button', { name: /save/i }));
await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('File type settings saved'));
expect(body).toEqual({ allowed_file_types: 'jpg,png' });
expect(admin.setSavingFileTypes).toHaveBeenNthCalledWith(1, true);
expect(admin.setSavingFileTypes).toHaveBeenLastCalledWith(false);
});
it('FE-ADMSET-019: a failing file-type save shows the generic error toast', async () => {
server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
const admin = renderTab();
fireEvent.click(within(card('Allowed File Types')).getByRole('button', { name: /save/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
expect(admin.toast.success).not.toHaveBeenCalled();
expect(admin.setSavingFileTypes).toHaveBeenLastCalledWith(false);
});
it('FE-ADMSET-020: maps key input and its visibility toggle', () => {
const admin = renderTab({ mapsKey: 'abc' });
const mapsInput = within(card('API Keys')).getAllByPlaceholderText('Enter key...')[0];
expect(mapsInput).toHaveAttribute('type', 'password');
fireEvent.change(mapsInput, { target: { value: 'abcd' } });
expect(admin.setMapsKey).toHaveBeenCalledWith('abcd');
fireEvent.click(mapsInput.parentElement!.querySelector('button')!);
expect(admin.toggleKey).toHaveBeenCalledWith('maps');
});
it('FE-ADMSET-021: showKeys switches both key inputs to plain text', () => {
renderTab({ showKeys: { maps: true, unsplash: true } });
const inputs = within(card('API Keys')).getAllByPlaceholderText('Enter key...');
expect(inputs[0]).toHaveAttribute('type', 'text');
expect(inputs[1]).toHaveAttribute('type', 'text');
});
it('FE-ADMSET-022: unsplash key input and its visibility toggle', () => {
const admin = renderTab({ unsplashKey: '' });
const unsplashInput = within(card('API Keys')).getAllByPlaceholderText('Enter key...')[1];
fireEvent.change(unsplashInput, { target: { value: 'unsplash-key' } });
expect(admin.setUnsplashKey).toHaveBeenCalledWith('unsplash-key');
fireEvent.click(unsplashInput.parentElement!.querySelector('button')!);
expect(admin.toggleKey).toHaveBeenCalledWith('unsplash');
});
it('FE-ADMSET-023: the maps Test button is disabled without a key', () => {
renderTab({ mapsKey: '' });
expect(within(card('API Keys')).getByRole('button', { name: /^test$/i })).toBeDisabled();
});
it('FE-ADMSET-024: the maps Test button validates the maps key', () => {
const admin = renderTab({ mapsKey: 'AIza-test' });
fireEvent.click(within(card('API Keys')).getByRole('button', { name: /^test$/i }));
expect(admin.handleValidateKey).toHaveBeenCalledWith('maps');
});
it('FE-ADMSET-025: shows a spinner while the maps key is validating', () => {
renderTab({ mapsKey: 'k', validating: { maps: true } });
const testBtn = within(card('API Keys')).getByRole('button', { name: /^test$/i });
expect(testBtn).toBeDisabled();
expect(testBtn.querySelector('svg.animate-spin')).toBeInTheDocument();
});
it('FE-ADMSET-026: renders the validation result for the maps key', () => {
const { unmount } = render(<Harness admin={buildAdminHook({ mapsKey: 'k', validation: { maps: true } })} />);
expect(screen.getByText('Connected')).toBeInTheDocument();
unmount();
render(<Harness admin={buildAdminHook({ mapsKey: 'k', validation: { maps: false } })} />);
expect(screen.getByText('Invalid')).toBeInTheDocument();
expect(screen.queryByText('Connected')).not.toBeInTheDocument();
});
it('FE-ADMSET-027: places photos toggle updates state, store and API', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/admin/places-photos', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ enabled: true });
})
);
const admin = renderTab({ placesPhotosEnabled: false });
fireEvent.click(toggleFor('Place Photos'));
expect(admin.setPlacesPhotosEnabledState).toHaveBeenCalledWith(true);
expect(admin.setPlacesPhotosEnabled).toHaveBeenCalledWith(true);
await waitFor(() => expect(body).toEqual({ enabled: true }));
});
it('FE-ADMSET-028: a failing places-photos update rolls the toggle back', async () => {
server.use(http.put('/api/admin/places-photos', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ placesPhotosEnabled: false });
fireEvent.click(toggleFor('Place Photos'));
await waitFor(() => expect(admin.setPlacesPhotosEnabledState).toHaveBeenLastCalledWith(false));
expect(admin.setPlacesPhotosEnabled).toHaveBeenLastCalledWith(false);
});
it('FE-ADMSET-029: places autocomplete toggle updates state and rolls back on failure', async () => {
server.use(http.put('/api/admin/places-autocomplete', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ placesAutocompleteEnabled: true });
fireEvent.click(toggleFor('Place Autocomplete'));
expect(admin.setPlacesAutocompleteEnabledState).toHaveBeenNthCalledWith(1, false);
await waitFor(() => expect(admin.setPlacesAutocompleteEnabledState).toHaveBeenLastCalledWith(true));
expect(admin.setPlacesAutocompleteEnabled).toHaveBeenLastCalledWith(true);
});
it('FE-ADMSET-030: places details toggle updates state and rolls back on failure', async () => {
server.use(http.put('/api/admin/places-details', () => HttpResponse.json({}, { status: 500 })));
const admin = renderTab({ placesDetailsEnabled: true });
fireEvent.click(toggleFor('Place Details'));
expect(admin.setPlacesDetailsEnabledState).toHaveBeenNthCalledWith(1, false);
await waitFor(() => expect(admin.setPlacesDetailsEnabledState).toHaveBeenLastCalledWith(true));
expect(admin.setPlacesDetailsEnabled).toHaveBeenLastCalledWith(true);
});
it('FE-ADMSET-031: shows the Open-Meteo info block', () => {
renderTab();
expect(screen.getByText('Weather Data')).toBeInTheDocument();
expect(screen.getByText('16-day forecast')).toBeInTheDocument();
});
it('FE-ADMSET-032: the API keys save button calls handleSaveApiKeys', () => {
const admin = renderTab();
fireEvent.click(within(card('API Keys')).getByRole('button', { name: /^save$/i }));
expect(admin.handleSaveApiKeys).toHaveBeenCalledTimes(1);
});
it('FE-ADMSET-033: display name, issuer and discovery URL update the OIDC config', () => {
render(<OidcHarness />);
const oidc = card(/single sign-on/i);
fireEvent.change(within(oidc).getByPlaceholderText('z.B. Google, Authentik, Keycloak'), {
target: { value: 'Authentik' },
});
fireEvent.change(within(oidc).getByPlaceholderText('https://accounts.google.com'), {
target: { value: 'https://auth.example.com' },
});
fireEvent.change(within(oidc).getByPlaceholderText(/openid-configuration$/), {
target: { value: 'https://auth.example.com/.well-known/openid-configuration' },
});
expect(screen.getByDisplayValue('Authentik')).toBeInTheDocument();
expect(screen.getByDisplayValue('https://auth.example.com')).toBeInTheDocument();
expect(
screen.getByDisplayValue('https://auth.example.com/.well-known/openid-configuration')
).toBeInTheDocument();
});
it('FE-ADMSET-034: client id and client secret update the OIDC config', () => {
render(<OidcHarness />);
const oidc = card(/single sign-on/i);
const clientId = within(oidc).getByText('Client ID').parentElement!.querySelector('input')!;
fireEvent.change(clientId, { target: { value: 'trek-client' } });
const clientSecret = within(oidc).getByText('Client Secret').parentElement!.querySelector('input')!;
fireEvent.change(clientSecret, { target: { value: 's3cr3t' } });
expect(clientId).toHaveValue('trek-client');
expect(clientSecret).toHaveValue('s3cr3t');
});
it('FE-ADMSET-035: masks the client secret placeholder once one is stored', () => {
renderTab({ oidcConfig: { ...EMPTY_OIDC, client_secret_set: true } });
expect(screen.getByPlaceholderText('••••••••')).toBeInTheDocument();
});
it('FE-ADMSET-036: saving OIDC omits an empty secret and toasts on success', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/admin/oidc', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
const admin = renderTab({
oidcConfig: { ...EMPTY_OIDC, issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' },
});
fireEvent.click(within(card(/single sign-on/i)).getByRole('button', { name: /^save$/i }));
await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('OIDC configuration saved'));
expect(body).toEqual({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP', discovery_url: '' });
});
it('FE-ADMSET-037: saving OIDC includes a freshly typed secret', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/admin/oidc', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
renderTab({
oidcConfig: { ...EMPTY_OIDC, issuer: 'https://idp', client_id: 'cid', client_secret: 'topsecret' },
});
fireEvent.click(within(card(/single sign-on/i)).getByRole('button', { name: /^save$/i }));
await waitFor(() => expect(body).toMatchObject({ client_secret: 'topsecret' }));
});
it('FE-ADMSET-038: a failing OIDC save surfaces the server error message', async () => {
server.use(http.put('/api/admin/oidc', () => HttpResponse.json({ error: 'Issuer unreachable' }, { status: 400 })));
const admin = renderTab();
fireEvent.click(within(card(/single sign-on/i)).getByRole('button', { name: /^save$/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Issuer unreachable'));
expect(admin.setSavingOidc).toHaveBeenNthCalledWith(1, true);
expect(admin.setSavingOidc).toHaveBeenLastCalledWith(false);
});
it('FE-ADMSET-039: the OIDC save button is disabled while saving', () => {
renderTab({ savingOidc: true });
expect(within(card(/single sign-on/i)).getByRole('button', { name: /^save$/i })).toBeDisabled();
});
it('FE-ADMSET-040: the danger zone opens the rotate-JWT modal', () => {
const admin = renderTab();
fireEvent.click(screen.getByRole('button', { name: /^rotate$/i }));
expect(admin.setShowRotateJwtModal).toHaveBeenCalledWith(true);
});
});
@@ -0,0 +1,26 @@
// FE-ADMSTAT-001 to FE-ADMSTAT-003
import { Users } from 'lucide-react';
import { describe, expect, it } from 'vitest';
import { render, screen } from '../../../tests/helpers/render';
import AdminStatCard from './AdminStatCard';
describe('AdminStatCard', () => {
it('FE-ADMSTAT-001: renders label and value', () => {
render(<AdminStatCard label="Users" value={42} icon={Users} />);
expect(screen.getByText('42')).toBeInTheDocument();
expect(screen.getByText('Users')).toBeInTheDocument();
});
it('FE-ADMSTAT-002: renders zero without animating away from it', () => {
render(<AdminStatCard label="Files" value={0} icon={Users} />);
expect(screen.getByText('0')).toBeInTheDocument();
});
it('FE-ADMSTAT-003: renders the passed icon component with the card icon classes', () => {
const { container } = render(<AdminStatCard label="Trips" value={7} icon={Users} />);
expect(container.querySelector('svg.w-5.h-5.text-content')).toBeInTheDocument();
});
});
@@ -0,0 +1,58 @@
// FE-ADMBAN-001 to FE-ADMBAN-005
import React from 'react';
import { describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen } from '../../../tests/helpers/render';
import { useTranslation } from '../../i18n';
import type { UpdateInfo } from './adminModel';
import AdminUpdateBanner from './AdminUpdateBanner';
function Harness({ updateInfo, onHowTo }: { updateInfo: UpdateInfo; onHowTo: () => void }) {
const { t } = useTranslation();
return <AdminUpdateBanner updateInfo={updateInfo} t={t} onHowTo={onHowTo} />;
}
function buildUpdateInfo(overrides: Partial<UpdateInfo> = {}): UpdateInfo {
return { update_available: true, latest: '3.5.0', current: '3.4.1', ...overrides };
}
describe('AdminUpdateBanner', () => {
it('FE-ADMBAN-001: shows the available headline', () => {
render(<Harness updateInfo={buildUpdateInfo()} onHowTo={() => {}} />);
expect(screen.getByText('Update available')).toBeInTheDocument();
});
it('FE-ADMBAN-002: interpolates latest and current version into the text', () => {
render(<Harness updateInfo={buildUpdateInfo()} onHowTo={() => {}} />);
expect(screen.getByText('TREK v3.5.0 is available. You are running v3.4.1.')).toBeInTheDocument();
});
it('FE-ADMBAN-003: hides the GitHub link when release_url is missing', () => {
render(<Harness updateInfo={buildUpdateInfo()} onHowTo={() => {}} />);
expect(screen.queryByRole('link', { name: /view on github/i })).not.toBeInTheDocument();
});
it('FE-ADMBAN-004: links to the release when release_url is set', () => {
render(
<Harness
updateInfo={buildUpdateInfo({ release_url: 'https://github.com/liketrek/TREK/releases/tag/v3.5.0' })}
onHowTo={() => {}}
/>
);
const link = screen.getByRole('link', { name: /view on github/i });
expect(link).toHaveAttribute('href', 'https://github.com/liketrek/TREK/releases/tag/v3.5.0');
expect(link).toHaveAttribute('target', '_blank');
});
it('FE-ADMBAN-005: calls onHowTo when the how-to button is clicked', () => {
const onHowTo = vi.fn();
render(<Harness updateInfo={buildUpdateInfo()} onHowTo={onHowTo} />);
fireEvent.click(screen.getByRole('button', { name: /how to update/i }));
expect(onHowTo).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,362 @@
// FE-ADMMOD-001 to FE-ADMMOD-027
import { http, HttpResponse } from 'msw';
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { server } from '../../../tests/helpers/msw/server';
import { fireEvent, render, screen, waitFor, within } from '../../../tests/helpers/render';
import { buildAdminHook, buildAdminUser, type AdminHook } from '../../../tests/helpers/mobileAdmin';
import { resetAllStores } from '../../../tests/helpers/store';
import { useTranslation } from '../../i18n';
import type { UpdateInfo } from './adminModel';
import AdminUserModals from './AdminUserModals';
type Spy = ReturnType<typeof vi.fn>;
type Spies = Record<string, Spy> & { toast: Record<string, Spy> };
function Harness({ admin }: { admin: AdminHook }) {
const { t } = useTranslation();
return <AdminUserModals admin={admin} t={t} />;
}
function renderModals(overrides: Record<string, unknown> = {}) {
const admin = buildAdminHook(overrides);
render(<Harness admin={admin} />);
return admin as unknown as Spies;
}
const alice = buildAdminUser({ id: 2, username: 'alice', email: 'alice@example.com', role: 'user' });
type UserForm = { username: string; email: string; role: string; password: string };
/**
* The form inputs hand their setter an updater that reads e.target.value lazily,
* so a spy call can no longer be replayed once React re-rendered the controlled
* input. These harnesses keep the form in real state instead.
*/
function CreateFormHarness() {
const { t } = useTranslation();
const [createForm, setCreateForm] = React.useState({ username: '', email: '', password: '', role: 'user' });
const admin = buildAdminHook({ showCreateUser: true, createForm, setCreateForm });
return <AdminUserModals admin={admin} t={t} />;
}
function EditFormHarness() {
const { t } = useTranslation();
const [editForm, setEditForm] = React.useState<UserForm>({
username: 'alice',
email: 'alice@example.com',
role: 'user',
password: '',
});
const admin = buildAdminHook({ editingUser: alice, editForm, setEditForm });
return <AdminUserModals admin={admin} t={t} />;
}
const editing = {
editingUser: alice,
editForm: { username: 'alice', email: 'alice@example.com', role: 'user', password: '' },
};
function buildUpdateInfo(overrides: Partial<UpdateInfo> = {}): UpdateInfo {
return { update_available: true, latest: '3.5.0', current: '3.4.1', ...overrides };
}
beforeEach(() => {
resetAllStores();
});
afterEach(() => {
server.resetHandlers();
});
describe('AdminUserModals', () => {
it('FE-ADMMOD-001: renders no modal content while everything is closed', () => {
renderModals();
expect(screen.queryByText('Create User')).not.toBeInTheDocument();
expect(screen.queryByText('Edit User')).not.toBeInTheDocument();
expect(screen.queryByText(/docker pull/)).not.toBeInTheDocument();
expect(screen.queryByText('Rotate JWT Secret')).not.toBeInTheDocument();
});
it('FE-ADMMOD-002: the create-user modal shows all four fields', () => {
renderModals({ showCreateUser: true });
expect(screen.getByPlaceholderText('Username')).toBeInTheDocument();
expect(screen.getByPlaceholderText('Email')).toBeInTheDocument();
expect(screen.getByPlaceholderText('Password')).toBeInTheDocument();
expect(screen.getByText('Role')).toBeInTheDocument();
});
it('FE-ADMMOD-003: create-user inputs write through setCreateForm', () => {
render(<CreateFormHarness />);
fireEvent.change(screen.getByPlaceholderText('Username'), { target: { value: 'bob' } });
fireEvent.change(screen.getByPlaceholderText('Email'), { target: { value: 'bob@example.com' } });
fireEvent.change(screen.getByPlaceholderText('Password'), { target: { value: 'hunter2hunter2' } });
expect(screen.getByPlaceholderText('Username')).toHaveValue('bob');
expect(screen.getByPlaceholderText('Email')).toHaveValue('bob@example.com');
expect(screen.getByPlaceholderText('Password')).toHaveValue('hunter2hunter2');
});
it('FE-ADMMOD-004: the create-user password can be revealed', () => {
renderModals({ showCreateUser: true });
const pw = screen.getByPlaceholderText('Password');
expect(pw).toHaveAttribute('type', 'password');
fireEvent.click(screen.getByRole('button', { name: /show or hide password/i }));
expect(pw).toHaveAttribute('type', 'text');
});
it('FE-ADMMOD-005: picking a role in the create modal stores it as a string', () => {
const admin = renderModals({ showCreateUser: true });
fireEvent.click(screen.getByRole('button', { name: 'User' }));
fireEvent.click(screen.getByText('Administrator'));
const base = { username: '', email: '', password: '', role: 'user' };
const updater = admin.setCreateForm.mock.calls[0][0] as (f: typeof base) => typeof base;
expect(updater(base).role).toBe('admin');
});
it('FE-ADMMOD-006: the create modal cancel and submit buttons are wired', () => {
const admin = renderModals({ showCreateUser: true });
fireEvent.click(screen.getByRole('button', { name: /^cancel$/i }));
expect(admin.setShowCreateUser).toHaveBeenCalledWith(false);
const buttons = screen.getAllByRole('button', { name: /create user/i });
fireEvent.click(buttons[buttons.length - 1]);
expect(admin.handleCreateUser).toHaveBeenCalledTimes(1);
});
it('FE-ADMMOD-007: the edit modal pre-fills the form from editForm', () => {
renderModals(editing);
expect(screen.getByDisplayValue('alice')).toBeInTheDocument();
expect(screen.getByDisplayValue('alice@example.com')).toBeInTheDocument();
expect(screen.getByPlaceholderText('Enter new password…')).toHaveValue('');
});
it('FE-ADMMOD-008: edit-modal inputs write through setEditForm', () => {
render(<EditFormHarness />);
fireEvent.change(screen.getByDisplayValue('alice'), { target: { value: 'alice2' } });
fireEvent.change(screen.getByDisplayValue('alice@example.com'), { target: { value: 'a2@example.com' } });
fireEvent.change(screen.getByPlaceholderText('Enter new password…'), { target: { value: 'newpassword1' } });
expect(screen.getByDisplayValue('alice2')).toBeInTheDocument();
expect(screen.getByDisplayValue('a2@example.com')).toBeInTheDocument();
expect(screen.getByPlaceholderText('Enter new password…')).toHaveValue('newpassword1');
});
it('FE-ADMMOD-009: the edit-modal password can be revealed', () => {
renderModals(editing);
const pw = screen.getByPlaceholderText('Enter new password…');
expect(pw).toHaveAttribute('type', 'password');
fireEvent.click(screen.getByRole('button', { name: /show or hide password/i }));
expect(pw).toHaveAttribute('type', 'text');
});
it('FE-ADMMOD-010: picking a role in the edit modal stores it as a string', () => {
const admin = renderModals(editing);
fireEvent.click(screen.getByRole('button', { name: 'User' }));
fireEvent.click(screen.getByText('Administrator'));
const base = { username: 'alice', email: 'alice@example.com', role: 'user', password: '' };
const updater = admin.setEditForm.mock.calls[0][0] as (f: typeof base) => typeof base;
expect(updater(base).role).toBe('admin');
});
it('FE-ADMMOD-011: the edit modal cancel and save buttons are wired', () => {
const admin = renderModals(editing);
fireEvent.click(screen.getByRole('button', { name: /^cancel$/i }));
expect(admin.setEditingUser).toHaveBeenCalledWith(null);
fireEvent.click(screen.getByRole('button', { name: /^save$/i }));
expect(admin.handleSaveUser).toHaveBeenCalledTimes(1);
});
it('FE-ADMMOD-012: resetting passkeys is skipped when the confirm is declined', () => {
vi.spyOn(window, 'confirm').mockReturnValue(false);
const admin = renderModals(editing);
fireEvent.click(screen.getByRole('button', { name: /reset passkeys/i }));
expect(window.confirm).toHaveBeenCalledWith('Remove all passkeys for alice?');
expect(admin.toast.success).not.toHaveBeenCalled();
});
it('FE-ADMMOD-013: a confirmed passkey reset reports how many were removed', async () => {
vi.spyOn(window, 'confirm').mockReturnValue(true);
let deletedFor: string | undefined;
server.use(
http.delete('/api/admin/users/:id/passkeys', ({ params }) => {
deletedFor = params.id as string;
return HttpResponse.json({ deleted: 3 });
})
);
const admin = renderModals(editing);
fireEvent.click(screen.getByRole('button', { name: /reset passkeys/i }));
await waitFor(() => expect(admin.toast.success).toHaveBeenCalledWith('Removed 3 passkey(s)'));
expect(deletedFor).toBe('2');
});
it('FE-ADMMOD-014: a failing passkey reset toasts the generic error', async () => {
vi.spyOn(window, 'confirm').mockReturnValue(true);
server.use(http.delete('/api/admin/users/:id/passkeys', () => HttpResponse.json({}, { status: 500 })));
const admin = renderModals(editing);
fireEvent.click(screen.getByRole('button', { name: /reset passkeys/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
});
it('FE-ADMMOD-015: the update popup shows the docker recipe by default', () => {
renderModals({ showUpdateModal: true, updateInfo: buildUpdateInfo() });
expect(screen.getByText('How to Update')).toBeInTheDocument();
expect(screen.getByText('v3.4.1 → v3.5.0')).toBeInTheDocument();
expect(screen.getByText(/docker pull mauriceboe\/trek:latest/)).toBeInTheDocument();
});
it('FE-ADMMOD-016: a non-docker install links to the wiki instead', () => {
renderModals({ showUpdateModal: true, updateInfo: buildUpdateInfo({ is_docker: false }) });
expect(screen.queryByText(/docker pull/)).not.toBeInTheDocument();
expect(screen.getByRole('link', { name: /open the update guide/i })).toHaveAttribute(
'href',
'https://github.com/liketrek/TREK/wiki/Updating'
);
});
it('FE-ADMMOD-017: the release link only renders when a release_url is known', () => {
const { unmount } = render(
<Harness admin={buildAdminHook({ showUpdateModal: true, updateInfo: buildUpdateInfo() })} />
);
expect(screen.queryByRole('link', { name: /view on github/i })).not.toBeInTheDocument();
unmount();
render(
<Harness
admin={buildAdminHook({
showUpdateModal: true,
updateInfo: buildUpdateInfo({ release_url: 'https://example.test/rel' }),
})}
/>
);
expect(screen.getByRole('link', { name: /view on github/i })).toHaveAttribute('href', 'https://example.test/rel');
});
it('FE-ADMMOD-018: the update popup closes from the Close button', () => {
const admin = renderModals({ showUpdateModal: true, updateInfo: buildUpdateInfo() });
fireEvent.click(screen.getByRole('button', { name: /close/i }));
expect(admin.setShowUpdateModal).toHaveBeenCalledWith(false);
});
it('FE-ADMMOD-019: the update popup closes on backdrop click but not on inner click', () => {
const admin = renderModals({ showUpdateModal: true, updateInfo: buildUpdateInfo() });
const inner = screen.getByText('How to Update').closest<HTMLElement>('div[style*="max-width"]')!;
fireEvent.click(inner);
expect(admin.setShowUpdateModal).not.toHaveBeenCalled();
fireEvent.click(inner.parentElement!);
expect(admin.setShowUpdateModal).toHaveBeenCalledWith(false);
});
it('FE-ADMMOD-020: the rotate-JWT modal explains the consequences', () => {
renderModals({ showRotateJwtModal: true });
expect(screen.getByText(/invalidate all sessions/i)).toBeInTheDocument();
expect(screen.getByRole('button', { name: /rotate .* log out/i })).toBeInTheDocument();
});
it('FE-ADMMOD-021: cancelling the rotate-JWT modal closes it', () => {
const admin = renderModals({ showRotateJwtModal: true });
fireEvent.click(screen.getByRole('button', { name: /^cancel$/i }));
expect(admin.setShowRotateJwtModal).toHaveBeenCalledWith(false);
});
it('FE-ADMMOD-022: confirming the rotation logs out and navigates to login', async () => {
let rotated = false;
server.use(
http.post('/api/admin/rotate-jwt-secret', () => {
rotated = true;
return HttpResponse.json({ success: true });
})
);
const admin = renderModals({ showRotateJwtModal: true });
fireEvent.click(screen.getByRole('button', { name: /rotate .* log out/i }));
expect(admin.setRotatingJwt).toHaveBeenCalledWith(true);
await waitFor(() => expect(rotated).toBe(true));
await waitFor(() => expect(admin.logout).toHaveBeenCalledTimes(1));
expect(admin.navigate).toHaveBeenCalledWith('/login', { state: { noRedirect: true } });
expect(admin.setShowRotateJwtModal).toHaveBeenCalledWith(false);
});
it('FE-ADMMOD-023: a failing rotation keeps the modal open and toasts', async () => {
server.use(http.post('/api/admin/rotate-jwt-secret', () => HttpResponse.json({}, { status: 500 })));
const admin = renderModals({ showRotateJwtModal: true });
fireEvent.click(screen.getByRole('button', { name: /rotate .* log out/i }));
await waitFor(() => expect(admin.toast.error).toHaveBeenCalledWith('Error'));
expect(admin.logout).not.toHaveBeenCalled();
expect(admin.setRotatingJwt).toHaveBeenLastCalledWith(false);
});
it('FE-ADMMOD-024: both rotate buttons are disabled while rotating', () => {
renderModals({ showRotateJwtModal: true, rotatingJwt: true });
expect(screen.getByRole('button', { name: /^cancel$/i })).toBeDisabled();
expect(screen.getByRole('button', { name: /rotate .* log out/i })).toBeDisabled();
});
it('FE-ADMMOD-025: the modal X button closes the create-user modal', () => {
const admin = renderModals({ showCreateUser: true });
const header = screen
.getByRole('heading', { name: 'Create User' })
.closest<HTMLElement>('div.flex.items-center.justify-between')!;
fireEvent.click(within(header).getByRole('button'));
expect(admin.setShowCreateUser).toHaveBeenCalledWith(false);
});
it('FE-ADMMOD-026: the modal X button closes the edit-user modal', () => {
const admin = renderModals(editing);
const header = screen
.getByRole('heading', { name: 'Edit User' })
.closest<HTMLElement>('div.flex.items-center.justify-between')!;
fireEvent.click(within(header).getByRole('button'));
expect(admin.setEditingUser).toHaveBeenCalledWith(null);
});
it('FE-ADMMOD-027: the modal X button closes the rotate-JWT modal', () => {
const admin = renderModals({ showRotateJwtModal: true });
const header = screen
.getByRole('heading', { name: 'Rotate JWT Secret' })
.closest<HTMLElement>('div.flex.items-center.justify-between')!;
fireEvent.click(within(header).getByRole('button'));
expect(admin.setShowRotateJwtModal).toHaveBeenCalledWith(false);
});
});
@@ -0,0 +1,259 @@
// FE-ADMUSR-001 to FE-ADMUSR-024
import React from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, within } from '../../../tests/helpers/render';
import { buildAdminHook, buildAdminUser, type AdminHook } from '../../../tests/helpers/mobileAdmin';
import { resetAllStores } from '../../../tests/helpers/store';
import { useTranslation } from '../../i18n';
import AdminUsersTab from './AdminUsersTab';
vi.mock('../../components/Admin/PermissionsPanel', () => ({
default: () => <div data-testid="permissions-panel" />,
}));
type Spies = Record<string, ReturnType<typeof vi.fn>>;
type InviteForm = { max_uses: number; expires_in_days: number | ''; trip_id: number | '' };
function Harness({ admin }: { admin: AdminHook }) {
const { t, locale } = useTranslation();
return <AdminUsersTab admin={admin} t={t} locale={locale} />;
}
function renderTab(overrides: Record<string, unknown> = {}) {
const admin = buildAdminHook(overrides);
render(<Harness admin={admin} />);
return admin as unknown as Spies;
}
/** Replays the functional updater a setInviteForm spy was called with. */
function replayInviteForm(spy: ReturnType<typeof vi.fn>, callIndex: number): InviteForm {
const updater = spy.mock.calls[callIndex][0] as (f: InviteForm) => InviteForm;
return updater({ max_uses: 1, expires_in_days: 7, trip_id: '' });
}
const alice = buildAdminUser({
id: 2,
username: 'alice',
email: 'alice@example.com',
role: 'user',
created_at: '2025-03-04T00:00:00.000Z',
last_login: '2025-06-01T10:30:00.000Z',
online: true,
});
const me = buildAdminUser({ id: 1, username: 'admin', email: 'admin@example.com', role: 'admin' });
function buildInvite(overrides: Record<string, unknown> = {}) {
return {
id: 10,
token: 'abcdefghijkl-rest-of-token',
max_uses: 3,
used_count: 1,
expires_at: null,
trip_title: null,
created_by_name: 'admin',
...overrides,
};
}
beforeEach(() => {
resetAllStores();
});
describe('AdminUsersTab', () => {
it('FE-ADMUSR-001: renders the spinner while loading instead of the table', () => {
renderTab({ isLoading: true, users: [me] });
expect(screen.queryByRole('table')).not.toBeInTheDocument();
expect(screen.queryByText('admin')).not.toBeInTheDocument();
});
it('FE-ADMUSR-002: renders one row per user with email and role badge', () => {
renderTab({ users: [me, alice], currentUser: me });
const aliceRow = screen.getByText('alice').closest('tr')!;
expect(within(aliceRow).getByText('alice@example.com')).toBeInTheDocument();
expect(within(aliceRow).getByText('User')).toBeInTheDocument();
const adminRow = screen.getByText('admin').closest('tr')!;
expect(within(adminRow).getByText('Administrator')).toBeInTheDocument();
});
it('FE-ADMUSR-003: shows the user count in the card subtitle', () => {
renderTab({ users: [me, alice] });
expect(screen.getByText('2 Users')).toBeInTheDocument();
});
it('FE-ADMUSR-004: marks the current user with the "(You)" hint', () => {
renderTab({ users: [me, alice], currentUser: me });
const adminRow = screen.getByText('admin').closest('tr')!;
expect(within(adminRow).getByText('(You)')).toBeInTheDocument();
});
it('FE-ADMUSR-005: renders the avatar image when avatar_url is set, initial otherwise', () => {
renderTab({
users: [buildAdminUser({ id: 3, username: 'bob', avatar_url: '/uploads/avatars/bob.jpg' }), alice],
});
expect(screen.getByRole('img', { name: 'bob' })).toHaveAttribute('src', '/uploads/avatars/bob.jpg');
// alice has no avatar → first letter fallback
expect(screen.getByText('A')).toBeInTheDocument();
});
it('FE-ADMUSR-006: renders an em dash when the user never logged in', () => {
renderTab({ users: [buildAdminUser({ id: 4, username: 'never', last_login: null })] });
expect(screen.getByText('—')).toBeInTheDocument();
});
it('FE-ADMUSR-007: opens the create-user modal from the header button', () => {
const admin = renderTab({ users: [me] });
fireEvent.click(screen.getByRole('button', { name: /create user/i }));
expect(admin.setShowCreateUser).toHaveBeenCalledWith(true);
});
it('FE-ADMUSR-008: edit button forwards the row user to handleEditUser', () => {
const admin = renderTab({ users: [me, alice], currentUser: me });
const editButtons = screen.getAllByTitle('Edit User');
fireEvent.click(editButtons[1]);
expect(admin.handleEditUser).toHaveBeenCalledWith(alice);
});
it('FE-ADMUSR-009: delete button forwards the row user to handleDeleteUser', () => {
const admin = renderTab({ users: [me, alice], currentUser: me });
const deleteButtons = screen.getAllByTitle('Delete user');
fireEvent.click(deleteButtons[1]);
expect(admin.handleDeleteUser).toHaveBeenCalledWith(alice);
});
it('FE-ADMUSR-010: the delete button of the current user is disabled', () => {
renderTab({ users: [me, alice], currentUser: me });
const deleteButtons = screen.getAllByTitle('Delete user');
expect(deleteButtons[0]).toBeDisabled();
expect(deleteButtons[1]).not.toBeDisabled();
});
it('FE-ADMUSR-011: shows the invite empty state when there are no invites', () => {
renderTab({ invites: [] });
expect(screen.getByText('No invite links created yet')).toBeInTheDocument();
});
it('FE-ADMUSR-012: renders an active invite with truncated token and usage', () => {
renderTab({ invites: [buildInvite()] });
expect(screen.getByText('abcdefghijkl...')).toBeInTheDocument();
expect(screen.getByText('Active')).toBeInTheDocument();
expect(screen.getByText(/1\/3 used/)).toBeInTheDocument();
expect(screen.getByText(/by admin/)).toBeInTheDocument();
});
it('FE-ADMUSR-013: renders unlimited uses as infinity', () => {
renderTab({ invites: [buildInvite({ max_uses: 0, used_count: 4 })] });
expect(screen.getByText(/4\/∞ used/)).toBeInTheDocument();
});
it('FE-ADMUSR-014: marks an invite past its expiry as expired and hides copy', () => {
renderTab({ invites: [buildInvite({ expires_at: '2020-01-01T00:00:00.000Z' })] });
expect(screen.getByText('Expired')).toBeInTheDocument();
expect(screen.queryByTitle('Copy link')).not.toBeInTheDocument();
});
it('FE-ADMUSR-015: marks an invite at its use limit as used up', () => {
renderTab({ invites: [buildInvite({ max_uses: 2, used_count: 2 })] });
expect(screen.getByText('Used up')).toBeInTheDocument();
});
it('FE-ADMUSR-016: shows the bound trip for a trip-scoped invite', () => {
renderTab({ invites: [buildInvite({ trip_title: 'Iceland' })] });
expect(screen.getByText(/adds to Iceland/)).toBeInTheDocument();
});
it('FE-ADMUSR-017: copy and delete buttons forward the invite token / id', () => {
const admin = renderTab({ invites: [buildInvite()] });
fireEvent.click(screen.getByTitle('Copy link'));
expect(admin.copyInviteLink).toHaveBeenCalledWith('abcdefghijkl-rest-of-token');
fireEvent.click(screen.getByTitle('Delete'));
expect(admin.handleDeleteInvite).toHaveBeenCalledWith(10);
});
it('FE-ADMUSR-018: create-invite modal picks max uses and expiry', () => {
const admin = renderTab({ showCreateInvite: true });
fireEvent.click(screen.getByRole('button', { name: '5×' }));
expect(replayInviteForm(admin.setInviteForm, 0).max_uses).toBe(5);
fireEvent.click(screen.getByRole('button', { name: '14d' }));
expect(replayInviteForm(admin.setInviteForm, 1).expires_in_days).toBe(14);
});
it('FE-ADMUSR-019: unlimited uses and never-expiring are selectable', () => {
const admin = renderTab({ showCreateInvite: true });
const infinityButtons = screen.getAllByRole('button', { name: '∞' });
fireEvent.click(infinityButtons[0]); // max_uses = 0
expect(replayInviteForm(admin.setInviteForm, 0).max_uses).toBe(0);
fireEvent.click(infinityButtons[1]); // expires_in_days = ''
expect(replayInviteForm(admin.setInviteForm, 1).expires_in_days).toBe('');
});
it('FE-ADMUSR-020: create-invite modal only offers the trip picker when trips exist', () => {
renderTab({ showCreateInvite: true, inviteTrips: [] });
expect(screen.queryByText('Add to trip (optional)')).not.toBeInTheDocument();
renderTab({ showCreateInvite: true, inviteTrips: [{ id: 7, title: 'Iceland' }] });
expect(screen.getByText('Add to trip (optional)')).toBeInTheDocument();
});
it('FE-ADMUSR-021: create-invite modal wires cancel and submit', () => {
const admin = renderTab({ showCreateInvite: true });
fireEvent.click(screen.getByRole('button', { name: /^cancel$/i }));
expect(admin.setShowCreateInvite).toHaveBeenCalledWith(false);
fireEvent.click(screen.getByRole('button', { name: /create & copy/i }));
expect(admin.handleCreateInvite).toHaveBeenCalledTimes(1);
});
it('FE-ADMUSR-022: selecting a trip in the picker stores its numeric id', () => {
const admin = renderTab({ showCreateInvite: true, inviteTrips: [{ id: 7, title: 'Iceland' }] });
fireEvent.click(screen.getByText('No trip'));
fireEvent.click(screen.getByText('Iceland'));
expect(replayInviteForm(admin.setInviteForm, 0).trip_id).toBe(7);
});
it('FE-ADMUSR-023: renders the permissions panel below the invite list', () => {
renderTab({});
expect(screen.getByTestId('permissions-panel')).toBeInTheDocument();
});
it('FE-ADMUSR-024: the invite modal X button closes it', () => {
const admin = renderTab({ showCreateInvite: true });
const header = screen
.getByRole('heading', { name: 'Create Link' })
.closest<HTMLElement>('div.flex.items-center.justify-between')!;
fireEvent.click(within(header).getByRole('button'));
expect(admin.setShowCreateInvite).toHaveBeenCalledWith(false);
});
});
+724
View File
@@ -0,0 +1,724 @@
// FE-ADMHOOK-001 to FE-ADMHOOK-045
import { http, HttpResponse } from 'msw';
import React from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { MemoryRouter } from 'react-router-dom';
import { buildAdmin, buildUser } from '../../../tests/helpers/factories';
import { server } from '../../../tests/helpers/msw/server';
import { act, renderHook, waitFor } from '../../../tests/helpers/render';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAuthStore } from '../../store/authStore';
import { useAdmin } from './useAdmin';
const toastCalls: { type: string; message: string }[] = [];
vi.mock('../../components/shared/Toast', () => ({
useToast: () => ({
success: (m: string) => toastCalls.push({ type: 'success', message: m }),
error: (m: string) => toastCalls.push({ type: 'error', message: m }),
warning: (m: string) => toastCalls.push({ type: 'warning', message: m }),
info: (m: string) => toastCalls.push({ type: 'info', message: m }),
}),
}));
function wrapper({ children }: { children: React.ReactNode }) {
return (
<MemoryRouter>
<TranslationProvider>{children}</TranslationProvider>
</MemoryRouter>
);
}
/** Mounts the hook and waits until the initial parallel loads have settled. */
async function mountAdmin() {
const view = renderHook(() => useAdmin(), { wrapper });
await waitFor(() => expect(view.result.current.isLoading).toBe(false));
return view;
}
const me = buildAdmin({ id: 1, username: 'admin', email: 'admin@example.com' });
const alice = buildUser({ id: 2, username: 'alice', email: 'alice@example.com' });
beforeEach(() => {
resetAllStores();
toastCalls.length = 0;
seedStore(useAuthStore, { isAuthenticated: true, user: me });
// The default handler hands out generated ids; the self-delete guard needs
// the admin row to match the signed-in user.
server.use(http.get('/api/admin/users', () => HttpResponse.json({ users: [me, alice] })));
});
afterEach(() => {
server.resetHandlers();
vi.restoreAllMocks();
});
describe('useAdmin', () => {
it('FE-ADMHOOK-001: loads users, stats and invites on mount', async () => {
const { result } = await mountAdmin();
expect(result.current.users.map(u => u.username)).toEqual(['admin', 'alice']);
expect(result.current.stats).toMatchObject({ totalUsers: 2, totalTrips: 5, totalPlaces: 42, totalFiles: 8 });
expect(result.current.invites).toEqual([]);
expect(result.current.activeTab).toBe('users');
});
it('FE-ADMHOOK-002: toasts when the initial load fails', async () => {
server.use(http.get('/api/admin/users', () => HttpResponse.json({}, { status: 500 })));
await mountAdmin();
expect(toastCalls).toContainEqual({ type: 'error', message: 'Failed to load admin data' });
});
it('FE-ADMHOOK-003: survives failing invite endpoints with empty lists', async () => {
server.use(
http.get('/api/admin/invites', () => HttpResponse.json({}, { status: 500 })),
http.get('/api/admin/invites/trips', () => HttpResponse.json({}, { status: 500 }))
);
const { result } = await mountAdmin();
expect(result.current.invites).toEqual([]);
expect(result.current.inviteTrips).toEqual([]);
expect(toastCalls).toEqual([]);
});
it('FE-ADMHOOK-004: reads the auth toggles out of the app config', async () => {
server.use(
http.get('/api/auth/app-config', () =>
HttpResponse.json({
password_login: false,
password_registration: false,
oidc_login: false,
oidc_registration: false,
env_override_oidc_only: true,
oidc_configured: true,
require_mfa: 1,
passkey_login: true,
passkey_configured: true,
allowed_file_types: 'jpg,png',
})
)
);
const { result } = await mountAdmin();
await waitFor(() => expect(result.current.passwordLogin).toBe(false));
expect(result.current.passwordRegistration).toBe(false);
expect(result.current.oidcLogin).toBe(false);
expect(result.current.oidcRegistration).toBe(false);
expect(result.current.envOverrideOidcOnly).toBe(true);
expect(result.current.oidcConfigured).toBe(true);
expect(result.current.requireMfa).toBe(true);
expect(result.current.passkeyLogin).toBe(true);
expect(result.current.passkeyConfigured).toBe(true);
expect(result.current.allowedFileTypes).toBe('jpg,png');
});
it('FE-ADMHOOK-005: falls back to allow_registration for both registration flags', async () => {
server.use(http.get('/api/auth/app-config', () => HttpResponse.json({ allow_registration: false })));
const { result } = await mountAdmin();
await waitFor(() => expect(result.current.passwordRegistration).toBe(false));
expect(result.current.oidcRegistration).toBe(false);
expect(result.current.passwordLogin).toBe(true);
});
it('FE-ADMHOOK-006: a failing app-config keeps the defaults', async () => {
server.use(http.get('/api/auth/app-config', () => HttpResponse.json({}, { status: 500 })));
const { result } = await mountAdmin();
expect(result.current.passwordLogin).toBe(true);
expect(result.current.allowedFileTypes).toContain('jpg');
});
it('FE-ADMHOOK-007: loads the stored API keys', async () => {
server.use(
http.get('/api/auth/me/settings', () =>
HttpResponse.json({
settings: { maps_api_key: 'maps-k', openweather_api_key: 'weather-k', unsplash_api_key: 'unsplash-k' },
})
)
);
const { result } = await mountAdmin();
await waitFor(() => expect(result.current.mapsKey).toBe('maps-k'));
expect(result.current.weatherKey).toBe('weather-k');
expect(result.current.unsplashKey).toBe('unsplash-k');
});
it('FE-ADMHOOK-008: a failing settings request leaves the keys empty', async () => {
server.use(http.get('/api/auth/me/settings', () => HttpResponse.json({}, { status: 500 })));
const { result } = await mountAdmin();
expect(result.current.mapsKey).toBe('');
});
it('FE-ADMHOOK-009: ignores a version check that reports no update', async () => {
const { result } = await mountAdmin();
expect(result.current.updateInfo).toBeNull();
});
it('FE-ADMHOOK-045: keeps an available update', async () => {
server.use(
http.get('/api/admin/version-check', () =>
HttpResponse.json({ update_available: true, latest: '9.9.9', current: '1.0.0' })
)
);
const { result } = await mountAdmin();
await waitFor(() => expect(result.current.updateInfo).toMatchObject({ latest: '9.9.9' }));
});
it('FE-ADMHOOK-010: loads the feature flags and app settings', async () => {
server.use(
http.get('/api/admin/bag-tracking', () => HttpResponse.json({ enabled: true })),
http.get('/api/admin/places-photos', () => HttpResponse.json({ enabled: false })),
http.get('/api/admin/places-autocomplete', () => HttpResponse.json({ enabled: false })),
http.get('/api/admin/places-details', () => HttpResponse.json({ enabled: false })),
http.get('/api/admin/collab-features', () =>
HttpResponse.json({ chat: false, notes: true, polls: false, whatsnext: true })
),
http.get('/api/auth/app-settings', () =>
HttpResponse.json({ smtp_host: 'mail.test', webauthn_rp_id: 'trek.test', webauthn_origins: 'https://trek.test' })
)
);
const { result } = await mountAdmin();
await waitFor(() => expect(result.current.bagTrackingEnabled).toBe(true));
expect(result.current.placesPhotosEnabled).toBe(false);
expect(result.current.placesAutocompleteEnabled).toBe(false);
expect(result.current.placesDetailsEnabled).toBe(false);
expect(result.current.collabFeatures).toEqual({ chat: false, notes: true, polls: false, whatsnext: true });
expect(result.current.smtpValues.smtp_host).toBe('mail.test');
expect(result.current.webauthnRpId).toBe('trek.test');
expect(result.current.webauthnOrigins).toBe('https://trek.test');
expect(result.current.smtpLoaded).toBe(true);
});
it('FE-ADMHOOK-011: marks smtp as loaded even when app-settings fails', async () => {
server.use(http.get('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 })));
const { result } = await mountAdmin();
await waitFor(() => expect(result.current.smtpLoaded).toBe(true));
expect(result.current.smtpValues).toEqual({});
});
it('FE-ADMHOOK-012: handleToggleAuthSetting applies the value optimistically', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
})
);
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleToggleAuthSetting('password_login', false, result.current.setPasswordLogin);
});
expect(body).toEqual({ password_login: false });
expect(result.current.passwordLogin).toBe(false);
});
it('FE-ADMHOOK-013: handleToggleAuthSetting rolls back and toasts on failure', async () => {
server.use(
http.put('/api/auth/app-settings', () => HttpResponse.json({ error: 'locked' }, { status: 400 }))
);
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleToggleAuthSetting('password_login', false, result.current.setPasswordLogin);
});
expect(result.current.passwordLogin).toBe(true);
expect(toastCalls).toContainEqual({ type: 'error', message: 'locked' });
});
it('FE-ADMHOOK-014: handleToggleRequireMfa mirrors the value into the auth store', async () => {
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleToggleRequireMfa(true);
});
expect(result.current.requireMfa).toBe(true);
expect(useAuthStore.getState().appRequireMfa).toBe(true);
expect(toastCalls).toContainEqual({ type: 'success', message: 'Saved' });
});
it('FE-ADMHOOK-015: handleToggleRequireMfa reverts on failure', async () => {
server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 })));
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleToggleRequireMfa(true);
});
expect(result.current.requireMfa).toBe(false);
expect(toastCalls.some(c => c.type === 'error')).toBe(true);
});
it('FE-ADMHOOK-016: handleSaveWebauthn trims and re-reads the app config', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/app-settings', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({});
}),
http.get('/api/auth/app-config', () => HttpResponse.json({ passkey_configured: true }))
);
const { result } = await mountAdmin();
act(() => {
result.current.setWebauthnRpId(' trek.test ');
result.current.setWebauthnOrigins(' https://trek.test ');
});
await act(async () => {
await result.current.handleSaveWebauthn();
});
expect(body).toEqual({ webauthn_rp_id: 'trek.test', webauthn_origins: 'https://trek.test' });
expect(result.current.passkeyConfigured).toBe(true);
expect(result.current.savingWebauthn).toBe(false);
});
it('FE-ADMHOOK-017: handleSaveWebauthn toasts and resets the flag on failure', async () => {
server.use(http.put('/api/auth/app-settings', () => HttpResponse.json({}, { status: 500 })));
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleSaveWebauthn();
});
expect(toastCalls.some(c => c.type === 'error')).toBe(true);
expect(result.current.savingWebauthn).toBe(false);
});
it('FE-ADMHOOK-018: toggleKey flips visibility per key', async () => {
const { result } = await mountAdmin();
act(() => result.current.toggleKey('maps'));
expect(result.current.showKeys).toEqual({ maps: true });
act(() => result.current.toggleKey('maps'));
expect(result.current.showKeys).toEqual({ maps: false });
});
it('FE-ADMHOOK-019: handleSaveApiKeys sends all three keys and toasts', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/me/api-keys', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ success: true });
})
);
const { result } = await mountAdmin();
act(() => {
result.current.setMapsKey('m');
result.current.setWeatherKey('w');
result.current.setUnsplashKey('u');
});
await act(async () => {
await result.current.handleSaveApiKeys();
});
expect(body).toMatchObject({ maps_api_key: 'm', openweather_api_key: 'w', unsplash_api_key: 'u' });
expect(toastCalls).toContainEqual({ type: 'success', message: 'API keys saved' });
expect(result.current.savingKeys).toBe(false);
});
it('FE-ADMHOOK-020: handleSaveApiKeys surfaces the thrown error message', async () => {
server.use(http.put('/api/auth/me/api-keys', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleSaveApiKeys();
});
expect(toastCalls.some(c => c.type === 'error')).toBe(true);
expect(result.current.savingKeys).toBe(false);
});
it('FE-ADMHOOK-021: handleValidateKeys stores the full validation result', async () => {
server.use(
http.put('/api/auth/me/api-keys', () => HttpResponse.json({ success: true })),
http.get('/api/auth/validate-keys', () => HttpResponse.json({ maps: true, weather: false }))
);
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleValidateKeys();
});
expect(result.current.validation).toEqual({ maps: true, weather: false });
expect(result.current.validating).toEqual({});
});
it('FE-ADMHOOK-022: handleValidateKeys toasts and clears the flags on failure', async () => {
server.use(http.get('/api/auth/validate-keys', () => HttpResponse.json({}, { status: 500 })));
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleValidateKeys();
});
expect(toastCalls).toContainEqual({ type: 'error', message: 'Error' });
expect(result.current.validating).toEqual({});
});
it('FE-ADMHOOK-023: handleValidateKey stores only the requested key', async () => {
server.use(
http.put('/api/auth/me/api-keys', () => HttpResponse.json({ success: true })),
http.get('/api/auth/validate-keys', () => HttpResponse.json({ maps: false, weather: true }))
);
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleValidateKey('maps');
});
expect(result.current.validation).toEqual({ maps: false });
expect(result.current.validating).toEqual({ maps: false });
});
it('FE-ADMHOOK-024: handleValidateKey toasts on failure', async () => {
server.use(http.get('/api/auth/validate-keys', () => HttpResponse.json({}, { status: 500 })));
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleValidateKey('maps');
});
expect(toastCalls).toContainEqual({ type: 'error', message: 'Error' });
expect(result.current.validating).toEqual({ maps: false });
});
it('FE-ADMHOOK-025: handleCreateUser rejects an incomplete form', async () => {
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleCreateUser();
});
expect(toastCalls).toContainEqual({
type: 'error',
message: 'Username, email and password are required',
});
expect(result.current.users).toHaveLength(2);
});
it('FE-ADMHOOK-026: handleCreateUser rejects a short password', async () => {
const { result } = await mountAdmin();
act(() => result.current.setCreateForm({ username: 'bob', email: 'b@e.com', password: 'short', role: 'user' }));
await act(async () => {
await result.current.handleCreateUser();
});
expect(toastCalls.some(c => c.type === 'error')).toBe(true);
expect(result.current.users).toHaveLength(2);
});
it('FE-ADMHOOK-027: handleCreateUser prepends the new user and resets the form', async () => {
const { result } = await mountAdmin();
act(() =>
result.current.setCreateForm({ username: 'bob', email: 'b@e.com', password: 'longenough1', role: 'admin' })
);
act(() => result.current.setShowCreateUser(true));
await act(async () => {
await result.current.handleCreateUser();
});
expect(result.current.users[0].username).toBe('bob');
expect(result.current.showCreateUser).toBe(false);
expect(result.current.createForm).toEqual({ username: '', email: '', password: '', role: 'user' });
expect(toastCalls).toContainEqual({ type: 'success', message: 'User created' });
});
it('FE-ADMHOOK-028: handleCreateUser surfaces the server error', async () => {
server.use(http.post('/api/admin/users', () => HttpResponse.json({ error: 'taken' }, { status: 409 })));
const { result } = await mountAdmin();
act(() =>
result.current.setCreateForm({ username: 'bob', email: 'b@e.com', password: 'longenough1', role: 'user' })
);
await act(async () => {
await result.current.handleCreateUser();
});
expect(toastCalls).toContainEqual({ type: 'error', message: 'taken' });
expect(result.current.users).toHaveLength(2);
});
it('FE-ADMHOOK-029: handleCreateInvite prepends the invite and copies the link', async () => {
const writeText = vi.fn(async () => undefined);
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, writable: true, configurable: true });
let body: Record<string, unknown> | null = null;
server.use(
http.post('/api/admin/invites', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ invite: { id: 7, token: 'tok-7' } });
})
);
const { result } = await mountAdmin();
act(() => result.current.setInviteForm({ max_uses: 3, expires_in_days: '', trip_id: '' }));
await act(async () => {
await result.current.handleCreateInvite();
});
expect(body).toEqual({ max_uses: 3, trip_id: null });
expect(result.current.invites[0]).toMatchObject({ token: 'tok-7' });
expect(result.current.inviteForm).toEqual({ max_uses: 1, expires_in_days: 7, trip_id: '' });
await waitFor(() => expect(writeText).toHaveBeenCalledWith(expect.stringContaining('/register?invite=tok-7')));
});
it('FE-ADMHOOK-030: handleCreateInvite forwards an explicit trip binding', async () => {
Object.defineProperty(navigator, 'clipboard', {
value: { writeText: vi.fn(async () => undefined) },
writable: true,
configurable: true,
});
let body: Record<string, unknown> | null = null;
server.use(
http.post('/api/admin/invites', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ invite: { id: 8, token: 'tok-8' } });
})
);
const { result } = await mountAdmin();
act(() => result.current.setInviteForm({ max_uses: 1, expires_in_days: 14, trip_id: 42 }));
await act(async () => {
await result.current.handleCreateInvite();
});
expect(body).toEqual({ max_uses: 1, expires_in_days: 14, trip_id: 42 });
});
it('FE-ADMHOOK-031: handleCreateInvite toasts the server error', async () => {
server.use(http.post('/api/admin/invites', () => HttpResponse.json({ error: 'no invites' }, { status: 400 })));
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleCreateInvite();
});
expect(toastCalls).toContainEqual({ type: 'error', message: 'no invites' });
});
it('FE-ADMHOOK-032: handleDeleteInvite removes it from the list', async () => {
server.use(
http.get('/api/admin/invites', () =>
HttpResponse.json({ invites: [{ id: 5, token: 'a' }, { id: 6, token: 'b' }] })
)
);
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleDeleteInvite(5);
});
expect(result.current.invites.map(i => i.id)).toEqual([6]);
expect(toastCalls).toContainEqual({ type: 'success', message: 'Invite link deleted' });
});
it('FE-ADMHOOK-033: a failing invite delete keeps the list intact', async () => {
server.use(
http.get('/api/admin/invites', () => HttpResponse.json({ invites: [{ id: 5, token: 'a' }] })),
http.delete('/api/admin/invites/:id', () => HttpResponse.json({}, { status: 500 }))
);
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleDeleteInvite(5);
});
expect(result.current.invites).toHaveLength(1);
expect(toastCalls).toContainEqual({ type: 'error', message: 'Failed to delete invite link' });
});
it('FE-ADMHOOK-034: copyInviteLink writes a full registration URL', async () => {
const writeText = vi.fn(async () => undefined);
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, writable: true, configurable: true });
const { result } = await mountAdmin();
act(() => result.current.copyInviteLink('tok-9'));
expect(writeText).toHaveBeenCalledWith(`${window.location.origin}/register?invite=tok-9`);
await waitFor(() => expect(toastCalls).toContainEqual({ type: 'success', message: 'Invite link copied to clipboard' }));
});
it('FE-ADMHOOK-035: handleEditUser seeds the edit form from the user', async () => {
const { result } = await mountAdmin();
const row = result.current.users[1];
act(() => result.current.handleEditUser(row));
expect(result.current.editingUser).toBe(row);
expect(result.current.editForm).toEqual({
username: 'alice',
email: 'alice@example.com',
role: 'user',
password: '',
});
});
it('FE-ADMHOOK-036: handleSaveUser sends the trimmed fields and replaces the row', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/admin/users/:id', async ({ params, request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ user: buildUser({ id: Number(params.id), username: 'alice2' }) });
})
);
const { result } = await mountAdmin();
act(() => result.current.handleEditUser(result.current.users[1]));
act(() => result.current.setEditForm({ username: ' alice2 ', email: ' a2@e.com ', role: 'admin', password: '' }));
await act(async () => {
await result.current.handleSaveUser();
});
expect(body).toEqual({ username: 'alice2', email: 'a2@e.com', role: 'admin' });
expect(result.current.users[1].username).toBe('alice2');
expect(result.current.editingUser).toBeNull();
expect(toastCalls).toContainEqual({ type: 'success', message: 'User updated' });
});
it('FE-ADMHOOK-037: handleSaveUser refuses a password shorter than eight characters', async () => {
let called = false;
server.use(
http.put('/api/admin/users/:id', () => {
called = true;
return HttpResponse.json({ user: buildUser({}) });
})
);
const { result } = await mountAdmin();
act(() => result.current.handleEditUser(result.current.users[1]));
act(() => result.current.setEditForm({ username: 'alice', email: 'a@e.com', role: 'user', password: 'short' }));
await act(async () => {
await result.current.handleSaveUser();
});
expect(called).toBe(false);
expect(result.current.editingUser).not.toBeNull();
expect(toastCalls.some(c => c.type === 'error')).toBe(true);
});
it('FE-ADMHOOK-038: handleSaveUser forwards a long enough password', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/admin/users/:id', async ({ params, request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ user: buildUser({ id: Number(params.id) }) });
})
);
const { result } = await mountAdmin();
act(() => result.current.handleEditUser(result.current.users[1]));
act(() =>
result.current.setEditForm({ username: 'alice', email: 'a@e.com', role: 'user', password: ' longenough1 ' })
);
await act(async () => {
await result.current.handleSaveUser();
});
expect(body).toMatchObject({ password: 'longenough1' });
});
it('FE-ADMHOOK-039: handleSaveUser surfaces the server error', async () => {
server.use(http.put('/api/admin/users/:id', () => HttpResponse.json({ error: 'conflict' }, { status: 409 })));
const { result } = await mountAdmin();
act(() => result.current.handleEditUser(result.current.users[1]));
await act(async () => {
await result.current.handleSaveUser();
});
expect(toastCalls).toContainEqual({ type: 'error', message: 'conflict' });
expect(result.current.editingUser).not.toBeNull();
});
it('FE-ADMHOOK-040: handleDeleteUser refuses to delete the signed-in admin', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleDeleteUser(result.current.users[0]);
});
expect(confirmSpy).not.toHaveBeenCalled();
expect(toastCalls).toContainEqual({ type: 'error', message: 'Cannot delete your own account' });
expect(result.current.users).toHaveLength(2);
});
it('FE-ADMHOOK-041: handleDeleteUser aborts when the confirm is declined', async () => {
vi.spyOn(window, 'confirm').mockReturnValue(false);
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleDeleteUser(result.current.users[1]);
});
expect(result.current.users).toHaveLength(2);
expect(toastCalls).toEqual([]);
});
it('FE-ADMHOOK-042: a confirmed delete removes the user from the list', async () => {
vi.spyOn(window, 'confirm').mockReturnValue(true);
let deletedId: string | undefined;
server.use(
http.delete('/api/admin/users/:id', ({ params }) => {
deletedId = params.id as string;
return HttpResponse.json({ success: true });
})
);
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleDeleteUser(result.current.users[1]);
});
expect(deletedId).toBe('2');
expect(result.current.users.map(u => u.username)).toEqual(['admin']);
expect(toastCalls).toContainEqual({ type: 'success', message: 'User deleted' });
});
it('FE-ADMHOOK-043: a failing delete surfaces the server error', async () => {
vi.spyOn(window, 'confirm').mockReturnValue(true);
server.use(http.delete('/api/admin/users/:id', () => HttpResponse.json({ error: 'busy' }, { status: 500 })));
const { result } = await mountAdmin();
await act(async () => {
await result.current.handleDeleteUser(result.current.users[1]);
});
expect(toastCalls).toContainEqual({ type: 'error', message: 'busy' });
expect(result.current.users).toHaveLength(2);
});
it('FE-ADMHOOK-044: mcpEnabled follows the addon store', async () => {
const { result } = await mountAdmin();
expect(result.current.mcpEnabled).toBe(false);
expect(result.current.hour12).toBe(false);
expect(result.current.currentUser?.username).toBe('admin');
});
});
+730
View File
@@ -0,0 +1,730 @@
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { http, HttpResponse } from 'msw';
import { render, act, waitFor } from '../../../tests/helpers/render';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildSettings } from '../../../tests/helpers/factories';
import { useSettingsStore } from '../../store/settingsStore';
import { A2_TO_A3 } from './atlasModel';
import { useAtlas } from './useAtlas';
// FE-HOOK-ATLAS-001 to FE-HOOK-ATLAS-030
interface MockGeoJson {
data: { features?: Record<string, unknown>[] };
options: Record<string, unknown>;
entries: { feature: Record<string, unknown>; layer: MockLayer }[];
styles: Record<string, unknown>[];
}
interface MockLayer {
handlers: Record<string, (e: unknown) => void>;
bindTooltip: ReturnType<typeof vi.fn>;
on: ReturnType<typeof vi.fn>;
setStyle: ReturnType<typeof vi.fn>;
getBounds: ReturnType<typeof vi.fn>;
}
const lf = vi.hoisted(() => ({
mapHandlers: {} as Record<string, ((e?: unknown) => void)[]>,
geoJson: [] as unknown[],
panes: {} as Record<string, { style: Record<string, string> }>,
zoom: 3,
intersects: true,
hasLayer: true,
boundsThrows: false,
mapsCreated: 0,
mapsRemoved: 0,
markers: 0,
reset() {
this.mapHandlers = {};
this.geoJson = [];
this.panes = { overlayPane: { style: {} } };
this.zoom = 3;
this.intersects = true;
this.hasLayer = true;
this.boundsThrows = false;
this.mapsCreated = 0;
this.mapsRemoved = 0;
this.markers = 0;
},
}));
vi.mock('leaflet', () => {
const makeLayer = () => {
const handlers: Record<string, (e: unknown) => void> = {};
const layer = {
handlers,
bindTooltip: vi.fn(() => layer),
on: vi.fn((event: string, cb: (e: unknown) => void) => { handlers[event] = cb; return layer; }),
setStyle: vi.fn(),
getBounds: vi.fn(() => {
if (lf.boundsThrows) throw new Error('no bounds');
return { isValid: () => true };
}),
};
return layer;
};
const map = {
setView: vi.fn(() => map),
on: vi.fn((event: string, cb: () => void) => { (lf.mapHandlers[event] ||= []).push(cb); return map; }),
off: vi.fn(() => map),
remove: vi.fn(() => { lf.mapsRemoved += 1; }),
fitBounds: vi.fn(),
addLayer: vi.fn(),
removeLayer: vi.fn(),
getZoom: vi.fn(() => lf.zoom),
getCenter: vi.fn(() => ({ lat: 25, lng: 0 })),
getBounds: vi.fn(() => ({ intersects: () => lf.intersects })),
hasLayer: vi.fn(() => lf.hasLayer),
createPane: vi.fn((name: string) => { lf.panes[name] = { style: {} }; }),
getPane: vi.fn((name: string) => lf.panes[name]),
};
const L = {
map: vi.fn(() => { lf.mapsCreated += 1; return map; }),
tileLayer: vi.fn(() => ({ addTo: vi.fn() })),
control: { zoom: vi.fn(() => ({ addTo: vi.fn() })) },
canvas: vi.fn(() => ({})),
svg: vi.fn(() => ({})),
divIcon: vi.fn(() => ({})),
marker: vi.fn(() => {
lf.markers += 1;
return { bindTooltip: vi.fn(() => ({})) };
}),
layerGroup: vi.fn(() => ({ addTo: vi.fn(() => ({})) })),
geoJSON: vi.fn((data: { features?: Record<string, unknown>[] }, options: Record<string, unknown>) => {
const record = { data, options, entries: [] as unknown[], styles: [] as unknown[] };
const style = options?.style as ((f: unknown) => unknown) | undefined;
const onEachFeature = options?.onEachFeature as ((f: unknown, l: unknown) => void) | undefined;
for (const feature of data?.features ?? []) {
if (style) record.styles.push(style(feature));
if (onEachFeature) {
const layer = makeLayer();
onEachFeature(feature, layer);
record.entries.push({ feature, layer });
}
}
lf.geoJson.push(record);
const result = {
addTo: vi.fn(() => result),
removeFrom: vi.fn(),
remove: vi.fn(),
clearLayers: vi.fn(),
resetStyle: vi.fn(),
};
return result;
}),
};
return { default: L, ...L };
});
const statsResponse = {
countries: [
{ code: 'FR', tripCount: 2, placeCount: 5, firstVisit: '2023-01-01', lastVisit: '2024-06-01' },
{ code: 'IT', tripCount: 0, placeCount: 0, firstVisit: null, lastVisit: null },
],
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 2, totalDays: 14, totalCities: 3 },
continents: { Europe: 2 },
lastTrip: null,
streak: 1,
tripsThisYear: 1,
};
const feature = (props: Record<string, unknown>) => ({ type: 'Feature', properties: props, geometry: null });
const geoCountries = {
type: 'FeatureCollection',
features: [
feature({ ISO_A2: 'FR', ADM0_A3: 'FRA', ISO_A3: 'FRA', NAME: 'France', ADMIN: 'France' }),
feature({ ISO_A2: 'IT', ADM0_A3: 'ITA', ISO_A3: 'ITA', NAME: 'Italy', ADMIN: 'Italy' }),
feature({ ISO_A2: 'DE', ADM0_A3: 'DEU', ISO_A3: 'DEU', NAME: 'Germany', ADMIN: 'Germany' }),
],
};
type Atlas = ReturnType<typeof useAtlas>;
let atlas: Atlas;
function Harness({ withPanel = true }: { withPanel?: boolean }): React.ReactElement {
atlas = useAtlas();
if (!withPanel) return <div ref={atlas.mapRef} />;
return (
<div>
<div ref={atlas.mapRef} />
<div ref={atlas.regionTooltipRef} data-testid="region-tooltip" />
<div ref={atlas.panelRef} data-testid="panel" />
<div ref={atlas.glareRef} data-testid="glare" />
<div ref={atlas.borderGlareRef} data-testid="border-glare" />
</div>
);
}
function useAtlasHandlers(over: Partial<Record<string, unknown>> = {}) {
server.use(
http.get('/api/addons/atlas/stats', () => HttpResponse.json(over.stats ?? statsResponse)),
http.get('/api/addons/atlas/bucket-list', () => HttpResponse.json({ items: over.bucket ?? [] })),
http.get('/api/addons/atlas/regions', () => HttpResponse.json({ regions: over.regions ?? {} })),
http.get('/api/addons/atlas/countries/geo', () => HttpResponse.json(over.geo ?? { type: 'FeatureCollection', features: [] })),
http.get('/api/addons/atlas/regions/geo', () => HttpResponse.json(over.regionGeo ?? { features: [] })),
http.get('/api/atlas-layers', () => HttpResponse.json({ layers: over.layers ?? [] })),
);
}
async function mountAtlas(over: Partial<Record<string, unknown>> = {}, props: { withPanel?: boolean } = {}) {
useAtlasHandlers(over);
const view = render(<Harness {...props} />);
await waitFor(() => expect(atlas.loading).toBe(false));
return view;
}
beforeEach(() => {
lf.reset();
resetAllStores();
seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: false }) });
});
afterEach(() => {
vi.unstubAllGlobals();
});
describe('useAtlas', () => {
it('FE-HOOK-ATLAS-001: loads stats, bucket list and visited regions on mount', async () => {
await mountAtlas({
bucket: [{ id: 1, name: 'Kyoto', lat: 35, lng: 135, country_code: 'JP', notes: null, target_date: null }],
regions: { FR: [{ code: 'FR-BRE', name: 'Bretagne', placeCount: 2 }] },
});
expect(atlas.stats.totalCountries).toBe(2);
expect(atlas.countries.map((c) => c.code)).toEqual(['FR', 'IT']);
expect(atlas.bucketList).toHaveLength(1);
await waitFor(() => expect(atlas.visitedRegions.FR).toHaveLength(1));
// A bucket item with coordinates becomes a map marker.
await waitFor(() => expect(lf.markers).toBe(1));
});
it('FE-HOOK-ATLAS-002: a failing stats request still ends the loading state', async () => {
useAtlasHandlers();
server.use(http.get('/api/addons/atlas/stats', () => HttpResponse.error()));
render(<Harness />);
await waitFor(() => expect(atlas.loading).toBe(false));
expect(atlas.data).toBeNull();
expect(atlas.stats).toEqual({ totalTrips: 0, totalPlaces: 0, totalCountries: 0, totalDays: 0 });
});
it('FE-HOOK-ATLAS-003: the country GeoJSON augments the alpha-2 to alpha-3 table', async () => {
await mountAtlas({
geo: {
type: 'FeatureCollection',
features: [
feature({ ISO_A2: 'ZZ', ADM0_A3: 'ZZZ', NAME: 'Testland' }),
feature({ ISO_A2: '-99', ADM0_A3: 'FRA', NAME: 'France' }),
feature({ ISO_A2: 'FR', ADM0_A3: 'XXX', NAME: 'France' }),
],
},
});
await waitFor(() => expect(A2_TO_A3.ZZ).toBe('ZZZ'));
// An existing mapping is never clobbered by a second dataset entry.
expect(A2_TO_A3.FR).toBe('FRA');
});
it('FE-HOOK-ATLAS-004: the country search options dedupe, fall back to alpha-3 and sort by label', async () => {
await mountAtlas({
geo: {
type: 'FeatureCollection',
features: [
feature({ ISO_A2: 'IT', ADM0_A3: 'ITA', NAME: 'Italy' }),
feature({ ISO_A2: '-99', ADM0_A3: 'FRA', NAME: 'France' }),
feature({ ISO_A2: 'IT', ADM0_A3: 'ITA', NAME: 'Italy again' }),
feature({ ISO_A2: '-99', ADM0_A3: '-99', NAME: 'Nowhere' }),
feature({ NAME: 'No codes at all' }),
],
},
});
await waitFor(() => expect(atlas.atlas_country_options.length).toBeGreaterThan(0));
expect(atlas.atlas_country_options.map((o) => o.code)).toEqual(['FR', 'IT']);
expect(atlas.atlas_country_options.map((o) => o.label)).toEqual(['France', 'Italy']);
});
it('FE-HOOK-ATLAS-005: the country name resolver falls back to the raw code', async () => {
// Intl.DisplayNames missing (older WebViews) — the hook must keep the identity resolver.
vi.stubGlobal('Intl', new Proxy(Intl, {
get: (target, prop, receiver) => (prop === 'DisplayNames' ? undefined : Reflect.get(target, prop, receiver)),
}));
await mountAtlas();
expect(atlas.resolveName('FR')).toBe('FR');
});
it('FE-HOOK-ATLAS-006: an unresolvable region code resolves to itself', async () => {
await mountAtlas();
expect(atlas.resolveName('not-a-region')).toBe('not-a-region');
});
it('FE-HOOK-ATLAS-007: the panel glare handlers bail out while the refs are unmounted', async () => {
await mountAtlas({}, { withPanel: false });
act(() => {
atlas.handlePanelMouseMove({ clientX: 10, clientY: 10 } as React.MouseEvent<HTMLDivElement>);
atlas.handlePanelMouseLeave();
});
expect(atlas.loading).toBe(false);
});
it('FE-HOOK-ATLAS-007b: the panel glare follows the cursor relative to the panel', async () => {
const view = await mountAtlas();
const panel = view.container.querySelector('[data-testid="panel"]') as HTMLElement;
const glare = view.container.querySelector('[data-testid="glare"]') as HTMLElement;
const borderGlare = view.container.querySelector('[data-testid="border-glare"]') as HTMLElement;
vi.spyOn(panel, 'getBoundingClientRect').mockReturnValue({ left: 20, top: 10 } as DOMRect);
act(() => {
atlas.handlePanelMouseMove({ clientX: 120, clientY: 60 } as React.MouseEvent<HTMLDivElement>);
});
expect(glare.style.opacity).toBe('1');
expect(glare.style.background).toContain('circle 300px at 100px 50px');
expect(borderGlare.style.opacity).toBe('1');
act(() => atlas.handlePanelMouseLeave());
expect(glare.style.opacity).toBe('0');
expect(borderGlare.style.opacity).toBe('0');
});
describe('confirm actions', () => {
it('FE-HOOK-ATLAS-008: executing without a pending action does nothing', async () => {
await mountAtlas();
await act(async () => { await atlas.executeConfirmAction(); });
expect(atlas.data?.countries).toHaveLength(2);
});
it('FE-HOOK-ATLAS-009: confirming a mark adds the country, its continent and the total', async () => {
await mountAtlas();
server.use(http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ ok: true })));
act(() => atlas.setConfirmAction({ type: 'mark', code: 'DE', name: 'Germany' }));
await act(async () => { await atlas.executeConfirmAction(); });
expect(atlas.confirmAction).toBeNull();
expect(atlas.data?.countries.map((c) => c.code)).toEqual(['FR', 'IT', 'DE']);
expect(atlas.data?.stats.totalCountries).toBe(3);
expect(atlas.data?.continents?.Europe).toBe(3);
});
it('FE-HOOK-ATLAS-010: marking a country that is already listed leaves the data alone', async () => {
await mountAtlas();
server.use(http.post('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ ok: true })));
act(() => atlas.setConfirmAction({ type: 'mark', code: 'FR', name: 'France' }));
await act(async () => { await atlas.executeConfirmAction(); });
expect(atlas.data?.countries).toHaveLength(2);
expect(atlas.data?.stats.totalCountries).toBe(2);
});
it('FE-HOOK-ATLAS-011: confirming an unmark removes the country and its regions', async () => {
await mountAtlas({ regions: { IT: [{ code: 'IT-62', name: 'Lazio', placeCount: 0 }] } });
server.use(http.delete('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ ok: true })));
await waitFor(() => expect(atlas.visitedRegions.IT).toBeDefined());
act(() => atlas.setConfirmAction({ type: 'unmark', code: 'IT', name: 'Italy' }));
await act(async () => { await atlas.executeConfirmAction(); });
expect(atlas.data?.countries.map((c) => c.code)).toEqual(['FR']);
expect(atlas.data?.stats.totalCountries).toBe(1);
expect(atlas.visitedRegions.IT).toBeUndefined();
expect(atlas.selectedCountry).toBeNull();
});
it('FE-HOOK-ATLAS-011b: unmarking survives atlas data that never loaded', async () => {
useAtlasHandlers();
server.use(
http.get('/api/addons/atlas/stats', () => HttpResponse.error()),
http.delete('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ ok: true })),
);
render(<Harness />);
await waitFor(() => expect(atlas.loading).toBe(false));
act(() => atlas.setConfirmAction({ type: 'unmark', code: 'IT', name: 'Italy' }));
await act(async () => { await atlas.executeConfirmAction(); });
expect(atlas.data).toBeNull();
expect(atlas.confirmAction).toBeNull();
});
it('FE-HOOK-ATLAS-012: a country with real places is never unmarked locally', async () => {
await mountAtlas();
server.use(http.delete('/api/addons/atlas/country/:code/mark', () => HttpResponse.json({ ok: true })));
act(() => atlas.setConfirmAction({ type: 'unmark', code: 'FR', name: 'France' }));
await act(async () => { await atlas.executeConfirmAction(); });
expect(atlas.data?.countries.map((c) => c.code)).toEqual(['FR', 'IT']);
expect(atlas.visitedRegions).toEqual({});
});
});
describe('bucket list', () => {
it('FE-HOOK-ATLAS-013: an empty name is not submitted', async () => {
await mountAtlas();
const post = vi.fn();
server.use(http.post('/api/addons/atlas/bucket-list', () => { post(); return HttpResponse.json({ item: {} }); }));
await act(async () => { await atlas.handleAddBucketItem(); });
expect(post).not.toHaveBeenCalled();
expect(atlas.bucketList).toHaveLength(0);
});
it('FE-HOOK-ATLAS-014: notes, coordinates and the picker month become the posted payload', async () => {
await mountAtlas();
let body: unknown = null;
server.use(
http.post('/api/addons/atlas/bucket-list', async ({ request }) => {
body = await request.json();
return HttpResponse.json({ item: { id: 7, name: 'Kyoto', lat: 35, lng: 135, country_code: null, notes: 'onsen', target_date: '2027-04' } });
}),
);
act(() => {
atlas.setBucketForm({ name: ' Kyoto ', notes: ' onsen ', lat: '35', lng: '135', target_date: '' });
atlas.setBucketPoiMonth(4);
atlas.setBucketPoiYear(2027);
atlas.setShowBucketAdd(true);
});
await act(async () => { await atlas.handleAddBucketItem(); });
expect(body).toEqual({ name: 'Kyoto', notes: 'onsen', lat: 35, lng: 135, target_date: '2027-04' });
expect(atlas.bucketList.map((i) => i.id)).toEqual([7]);
expect(atlas.bucketForm).toEqual({ name: '', notes: '', lat: '', lng: '', target_date: '' });
expect(atlas.showBucketAdd).toBe(false);
expect(atlas.bucketPoiMonth).toBe(0);
});
it('FE-HOOK-ATLAS-015: an explicit target date wins over the month picker', async () => {
await mountAtlas();
let body: unknown = null;
server.use(
http.post('/api/addons/atlas/bucket-list', async ({ request }) => {
body = await request.json();
return HttpResponse.json({ item: { id: 8 } });
}),
);
act(() => {
atlas.setBucketForm({ name: 'Lisbon', notes: '', lat: '', lng: '', target_date: '2030-01' });
atlas.setBucketPoiMonth(4);
atlas.setBucketPoiYear(2027);
});
await act(async () => { await atlas.handleAddBucketItem(); });
expect(body).toEqual({ name: 'Lisbon', target_date: '2030-01' });
});
it('FE-HOOK-ATLAS-016: a rejected add leaves the form untouched', async () => {
await mountAtlas();
server.use(http.post('/api/addons/atlas/bucket-list', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
act(() => atlas.setBucketForm({ name: 'Lisbon', notes: '', lat: '', lng: '', target_date: '' }));
await act(async () => { await atlas.handleAddBucketItem(); });
expect(atlas.bucketList).toHaveLength(0);
expect(atlas.bucketForm.name).toBe('Lisbon');
});
it('FE-HOOK-ATLAS-017: deleting drops the item, a failure keeps it', async () => {
await mountAtlas({ bucket: [{ id: 3, name: 'Kyoto', lat: null, lng: null, country_code: 'JP', notes: null, target_date: null }] });
server.use(http.delete('/api/addons/atlas/bucket-list/:id', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
await act(async () => { await atlas.handleDeleteBucketItem(3); });
expect(atlas.bucketList).toHaveLength(1);
server.use(http.delete('/api/addons/atlas/bucket-list/:id', () => HttpResponse.json({ ok: true })));
await act(async () => { await atlas.handleDeleteBucketItem(3); });
expect(atlas.bucketList).toHaveLength(0);
});
it('FE-HOOK-ATLAS-018: the POI search skips a blank query, stores results and survives failures', async () => {
await mountAtlas();
const search = vi.fn();
server.use(http.post('/api/maps/search', () => { search(); return HttpResponse.json({ places: [{ name: 'Kyoto', lat: 35, lng: 135 }] }); }));
await act(async () => { await atlas.handleBucketPoiSearch(); });
expect(search).not.toHaveBeenCalled();
act(() => atlas.setBucketSearch('kyoto'));
await act(async () => { await atlas.handleBucketPoiSearch(); });
expect(atlas.bucketSearchResults).toHaveLength(1);
expect(atlas.bucketSearching).toBe(false);
vi.spyOn(console, 'error').mockImplementation(() => {});
server.use(http.post('/api/maps/search', () => HttpResponse.error()));
await act(async () => { await atlas.handleBucketPoiSearch(); });
expect(atlas.bucketSearching).toBe(false);
});
it('FE-HOOK-ATLAS-019: picking a POI fills the form and clears the search', async () => {
await mountAtlas();
act(() => {
atlas.setBucketPoiMonth(4);
atlas.setBucketPoiYear(2027);
atlas.setBucketSearch('kyoto');
});
act(() => atlas.handleSelectBucketPoi({ name: 'Kyoto', lat: 35.1, lng: 135.2 }));
expect(atlas.bucketForm).toEqual({ name: 'Kyoto', notes: '', lat: '35.1', lng: '135.2', target_date: '2027-04' });
expect(atlas.bucketSearch).toBe('');
expect(atlas.bucketSearchResults).toHaveLength(0);
act(() => atlas.setBucketSearch('fallback'));
act(() => atlas.handleSelectBucketPoi({}));
expect(atlas.bucketForm.name).toBe('fallback');
expect(atlas.bucketForm.lat).toBe('');
});
});
describe('country selection', () => {
it('FE-HOOK-ATLAS-020: selecting a visited country with data loads its detail', async () => {
await mountAtlas({ geo: geoCountries });
server.use(http.get('/api/addons/atlas/country/:code', () => HttpResponse.json({ places: [], trips: [{ id: 1, title: 'Paris' }], manually_marked: false })));
await waitFor(() => expect(atlas.atlas_country_options.length).toBe(3));
await act(async () => { atlas.select_country_from_search('FR'); });
expect(atlas.atlas_country_search).toBe(atlas.resolveName('FR'));
expect(atlas.atlas_country_open).toBe(false);
await waitFor(() => expect(atlas.countryDetail?.trips).toHaveLength(1));
expect(atlas.selectedCountry).toBe('FR');
});
it('FE-HOOK-ATLAS-021: a failing detail request leaves the selection without a detail', async () => {
await mountAtlas({ geo: geoCountries });
server.use(http.get('/api/addons/atlas/country/:code', () => HttpResponse.json({ error: 'boom' }, { status: 500 })));
await act(async () => { await atlas.loadCountryDetail('FR'); });
expect(atlas.selectedCountry).toBe('FR');
expect(atlas.countryDetail).toBeNull();
});
it('FE-HOOK-ATLAS-022: selecting a visited but empty country offers to remove it', async () => {
await mountAtlas({ geo: geoCountries });
await waitFor(() => expect(atlas.atlas_country_options.length).toBe(3));
await act(async () => { atlas.select_country_from_search('IT'); });
expect(atlas.confirmAction).toEqual({ type: 'unmark', code: 'IT', name: atlas.resolveName('IT') });
});
it('FE-HOOK-ATLAS-023: selecting an unvisited country opens the mark/bucket choice', async () => {
await mountAtlas({ geo: geoCountries });
await waitFor(() => expect(atlas.atlas_country_options.length).toBe(3));
await act(async () => { atlas.select_country_from_search('DE'); });
expect(atlas.confirmAction).toEqual({ type: 'choose', code: 'DE', name: atlas.resolveName('DE') });
});
it('FE-HOOK-ATLAS-024: a layer without usable bounds does not break the fly-to', async () => {
await mountAtlas({ geo: geoCountries });
await waitFor(() => expect(atlas.atlas_country_options.length).toBe(3));
vi.spyOn(console, 'error').mockImplementation(() => {});
lf.boundsThrows = true;
await act(async () => { atlas.select_country_from_search('DE'); });
expect(atlas.confirmAction?.code).toBe('DE');
});
});
describe('map layers', () => {
it('FE-HOOK-ATLAS-025: country layers bind hover styling and the unmark click', async () => {
await mountAtlas({ geo: geoCountries });
await waitFor(() => expect(lf.geoJson.length).toBeGreaterThan(0));
const countryLayer = lf.geoJson[0] as MockGeoJson;
const it = countryLayer.entries.find((e) => (e.feature.properties as Record<string, string>).ISO_A2 === 'IT');
const de = countryLayer.entries.find((e) => (e.feature.properties as Record<string, string>).ISO_A2 === 'DE');
// Visited countries get a colour fill, unvisited ones the neutral one.
expect((countryLayer.styles[0] as { fillOpacity: number }).fillOpacity).toBe(0.7);
expect((countryLayer.styles[2] as { fillOpacity: number }).fillOpacity).toBe(0.3);
act(() => it!.layer.handlers.mouseover({ target: it!.layer }));
expect(it!.layer.setStyle).toHaveBeenCalledWith(expect.objectContaining({ fillOpacity: 0.9 }));
act(() => it!.layer.handlers.mouseout({ target: it!.layer }));
// IT has no trips and no places, so a click offers to remove it again.
act(() => it!.layer.handlers.click({}));
expect(atlas.confirmAction).toEqual({ type: 'unmark', code: 'IT', name: atlas.resolveName('IT') });
act(() => de!.layer.handlers.mouseover({ target: de!.layer }));
expect(de!.layer.setStyle).toHaveBeenCalledWith(expect.objectContaining({ fillOpacity: 0.5 }));
act(() => de!.layer.handlers.mouseout({ target: de!.layer }));
act(() => de!.layer.handlers.click({}));
expect(atlas.confirmAction).toEqual({ type: 'choose', code: 'DE', name: 'Germany' });
});
it('FE-HOOK-ATLAS-026: plugin tint layers are drawn in their own pane and redrawn on theme change', async () => {
await mountAtlas({
geo: geoCountries,
layers: [{ pluginId: 'p1', id: 'l1', countries: [{ code: 'FR', tone: 'success' }, { code: 'DE', tone: 'default' }] }],
});
const tint = await waitFor(() => {
const hit = (lf.geoJson as MockGeoJson[]).find((g) => g.options.pane === 'atlasPluginPane');
expect(hit).toBeTruthy();
return hit as MockGeoJson;
});
expect(tint.data.features).toHaveLength(2);
expect(lf.panes.atlasPluginPane.style.pointerEvents).toBe('none');
const style = tint.options.style as (f: unknown) => { fillColor: string };
expect(style(feature({ ADM0_A3: 'FRA' })).fillColor).toBe('#10b981');
expect(style(feature({ ADM0_A3: 'DEU' })).fillColor).toBe('#4F46E5');
const before = lf.geoJson.length;
act(() => { seedStore(useSettingsStore, { settings: buildSettings({ dark_mode: true }) }); });
await waitFor(() => expect(lf.geoJson.length).toBeGreaterThan(before));
expect(lf.mapsRemoved).toBeGreaterThan(0);
});
it('FE-HOOK-ATLAS-027: a plugin layer naming no country in the map draws nothing', async () => {
await mountAtlas({
geo: geoCountries,
layers: [{ pluginId: 'p1', id: 'l1', countries: [{ code: 'JP', tone: 'warn' }] }],
});
await waitFor(() => expect(atlas.atlas_country_options.length).toBe(3));
expect((lf.geoJson as MockGeoJson[]).some((g) => g.options.pane === 'atlasPluginPane')).toBe(false);
});
it('FE-HOOK-ATLAS-028: a failing plugin request simply leaves the map untinted', async () => {
useAtlasHandlers({ geo: geoCountries });
server.use(http.get('/api/atlas-layers', () => HttpResponse.error()));
render(<Harness />);
await waitFor(() => expect(atlas.loading).toBe(false));
await waitFor(() => expect(atlas.atlas_country_options.length).toBe(3));
expect((lf.geoJson as MockGeoJson[]).some((g) => g.options.pane === 'atlasPluginPane')).toBe(false);
});
it('FE-HOOK-ATLAS-029: zooming in loads the regions in view and zooming out hides the layer', async () => {
const regionGeo = {
type: 'FeatureCollection',
features: [
feature({ iso_a2: 'fr', iso_3166_2: 'FR-BRE', name: 'Bretagne', name_en: 'Brittany', admin: 'France' }),
feature({ iso_a2: 'fr', iso_3166_2: 'FR-IDF', name: 'Île-de-France', name_en: 'Ile-de-France', admin: 'France' }),
],
};
await mountAtlas({
geo: geoCountries,
regions: { FR: [{ code: 'FR-BRE', name: 'Bretagne', placeCount: 3 }] },
regionGeo,
});
await waitFor(() => expect(atlas.visitedRegions.FR).toHaveLength(1));
await waitFor(() => expect(lf.mapHandlers.zoomend?.length).toBeGreaterThan(0));
lf.zoom = 6;
lf.hasLayer = false;
act(() => { lf.mapHandlers.zoomend?.forEach((cb) => cb()); });
expect(lf.panes.overlayPane.style.opacity).toBe('0.35');
const regionLayer = await waitFor(() => {
const hit = (lf.geoJson as MockGeoJson[]).find((g) => g.options.pane === 'regionPane');
expect(hit).toBeTruthy();
return hit as MockGeoJson;
});
const style = regionLayer.options.style as (f: unknown) => { fillOpacity: number };
expect(style(regionGeo.features[0]).fillOpacity).toBe(0.85);
expect(style(regionGeo.features[1]).fillOpacity).toBe(0.03);
const [visited, unvisited] = regionLayer.entries;
act(() => visited.layer.handlers.mouseover({ target: visited.layer, originalEvent: { clientX: 40, clientY: 80 } }));
act(() => visited.layer.handlers.mousemove({ originalEvent: { clientX: 42, clientY: 82 } }));
act(() => visited.layer.handlers.mouseout({ target: visited.layer }));
act(() => visited.layer.handlers.click({}));
expect(atlas.confirmAction).toEqual({
type: 'unmark-region', code: 'FR', name: 'Bretagne', regionCode: 'FR-BRE', countryName: 'France',
});
act(() => unvisited.layer.handlers.mouseover({ target: unvisited.layer, originalEvent: { clientX: 10, clientY: 20 } }));
act(() => unvisited.layer.handlers.click({}));
expect(atlas.confirmAction).toEqual({
type: 'choose-region', code: 'FR', name: 'Île-de-France', regionCode: 'FR-IDF', countryName: 'France',
});
// Zooming again re-attaches the existing layer and skips the cached countries.
const drawn = lf.geoJson.length;
act(() => { lf.mapHandlers.zoomend?.forEach((cb) => cb()); });
expect(lf.geoJson.length).toBe(drawn);
// Zooming back out removes the region layer from the map again.
lf.zoom = 4;
lf.hasLayer = true;
act(() => { lf.mapHandlers.zoomend?.forEach((cb) => cb()); });
expect(lf.panes.overlayPane.style.opacity).toBe('1');
});
it('FE-HOOK-ATLAS-029b: regions match by english name and countries without visits stay unvisited', async () => {
const regionGeo = {
type: 'FeatureCollection',
features: [
feature({ iso_a2: 'fr', iso_3166_2: 'FR-BRE', name: 'Bretagne', name_en: 'Brittany', admin: 'France' }),
feature({ iso_a2: 'it', iso_3166_2: 'IT-62', name: 'Lazio', name_en: 'Latium', admin: 'Italy' }),
],
};
await mountAtlas({
geo: geoCountries,
// The cached region name only matches the bundle's english name.
regions: { FR: [{ code: 'FR-UNKNOWN', name: 'Brittany', placeCount: 1 }] },
regionGeo,
});
await waitFor(() => expect(lf.mapHandlers.zoomend?.length).toBeGreaterThan(0));
lf.zoom = 6;
act(() => { lf.mapHandlers.zoomend?.forEach((cb) => cb()); });
const regionLayer = await waitFor(() => {
const hit = (lf.geoJson as MockGeoJson[]).find((g) => g.options.pane === 'regionPane');
expect(hit).toBeTruthy();
return hit as MockGeoJson;
});
const style = regionLayer.options.style as (f: unknown) => { fillOpacity: number };
expect(style(regionGeo.features[0]).fillOpacity).toBe(0.85);
// Italy has no visited regions at all, so its feature stays an outline.
expect(style(regionGeo.features[1]).fillOpacity).toBe(0.03);
});
it('FE-HOOK-ATLAS-029c: a region response without features is ignored', async () => {
await mountAtlas({ geo: geoCountries, regionGeo: {} });
await waitFor(() => expect(lf.mapHandlers.zoomend?.length).toBeGreaterThan(0));
lf.zoom = 6;
await act(async () => { lf.mapHandlers.zoomend?.forEach((cb) => cb()); });
expect((lf.geoJson as MockGeoJson[]).some((g) => g.options.pane === 'regionPane')).toBe(false);
});
it('FE-HOOK-ATLAS-030: panning at low zoom does not refetch regions', async () => {
await mountAtlas({ geo: geoCountries, regionGeo: { features: [] } });
await waitFor(() => expect(atlas.atlas_country_options.length).toBe(3));
lf.zoom = 4;
act(() => { lf.mapHandlers.moveend?.forEach((cb) => cb()); });
lf.zoom = 6;
lf.intersects = false;
act(() => { lf.mapHandlers.moveend?.forEach((cb) => cb()); });
expect((lf.geoJson as MockGeoJson[]).some((g) => g.options.pane === 'regionPane')).toBe(false);
});
});
});
@@ -10,6 +10,9 @@ import {
presentLabels,
mappablePlaces,
normalizeLinkUrl,
nextStatus,
STATUS_META,
STATUS_ORDER,
} from './collectionsModel';
import type { CollectionLabel } from '@trek/shared';
@@ -186,6 +189,25 @@ describe('collectionsModel', () => {
expect(sortPlaces(places).map(p => p.id)).toEqual([2, 1]);
});
it('FE-COLLECTIONS-MODEL-038: name_asc sorts alphabetically, ignoring sort_order', () => {
const places = [
cp({ id: 1, name: 'Zoo', status: 'idea', sort_order: 0 }),
cp({ id: 2, name: 'anchor', status: 'idea', sort_order: 1 }),
cp({ id: 3, name: 'Bar', status: 'idea', sort_order: 2 }),
];
// localeCompare is case-insensitive here, so "anchor" sorts before "Bar".
expect(sortPlaces(places, 'name_asc').map(p => p.name)).toEqual(['anchor', 'Bar', 'Zoo']);
});
it('FE-COLLECTIONS-MODEL-039: name_asc leaves the input array untouched', () => {
const places = [
cp({ id: 1, name: 'B', status: 'idea' }),
cp({ id: 2, name: 'A', status: 'idea' }),
];
sortPlaces(places, 'name_asc');
expect(places.map(p => p.name)).toEqual(['B', 'A']);
});
it('FE-COLLECTIONS-MODEL-013: does not mutate the input array', () => {
const places = [
cp({ id: 1, name: 'A', status: 'idea', sort_order: 2 }),
@@ -317,6 +339,32 @@ describe('collectionsModel', () => {
});
});
// ── status metadata + cycle ─────────────────────────────────────────────────
describe('status metadata', () => {
it('FE-COLLECTIONS-MODEL-040: nextStatus cycles idea → want → visited → idea', () => {
expect(nextStatus('idea')).toBe('want');
expect(nextStatus('want')).toBe('visited');
expect(nextStatus('visited')).toBe('idea');
});
it('FE-COLLECTIONS-MODEL-041: STATUS_ORDER holds every status exactly once', () => {
expect(STATUS_ORDER).toEqual(['idea', 'want', 'visited']);
});
it('FE-COLLECTIONS-MODEL-042: every status has a label key, an icon and both colours', () => {
for (const status of STATUS_ORDER) {
const meta = STATUS_META[status];
expect(meta.labelKey).toBe(`collections.status.${status}`);
expect(meta.icon).toBeDefined();
expect(meta.color).toBeTruthy();
expect(meta.coverColor).toMatch(/^#/);
}
// Each status is visually distinct — no two share an icon.
const icons = STATUS_ORDER.map(s => STATUS_META[s].icon);
expect(new Set(icons).size).toBe(STATUS_ORDER.length);
});
});
// ── normalizeLinkUrl ────────────────────────────────────────────────────────
describe('normalizeLinkUrl', () => {
it('FE-COLLECTIONS-MODEL-026: prepends https:// to a scheme-less host', () => {
@@ -383,5 +431,22 @@ describe('collectionsModel', () => {
const opts = presentLabels(labels, places);
expect(opts.map(o => [o.id, o.count])).toEqual([[10, 2], [11, 2], [12, 0]]);
});
it('FE-COLLECTIONS-MODEL-043: a place saved before labels existed (no label_ids) is filtered out, not counted', () => {
const legacy = [
cp({ id: 7, name: 'Legacy', status: 'idea' }), // no label_ids at all
cp({ id: 8, name: 'Tagged', status: 'idea', label_ids: [10] }),
];
expect(filterPlaces(legacy, 'all', '', 'all', [10]).map(p => p.id)).toEqual([8]);
expect(presentLabels(labels, legacy).map(o => o.count)).toEqual([1, 0, 0]);
});
it('FE-COLLECTIONS-MODEL-044: presentLabels defaults a missing colour to null', () => {
expect(presentLabels(labels, [])).toEqual([
{ id: 10, name: 'Berlin', color: '#f00', count: 0 },
{ id: 11, name: 'Hamburg', color: '#00f', count: 0 },
{ id: 12, name: 'Unused', color: null, count: 0 },
]);
});
});
});
@@ -0,0 +1,971 @@
// FE-PAGE-COLL-001 to FE-PAGE-COLL-061
// The Collections page hook. The collection store is replaced by a fixture so
// every handler/branch can be driven directly; the categories request goes
// through MSW, and the websocket module is already mocked in tests/setup.ts.
import React from 'react'
import { act, renderHook, waitFor } from '@testing-library/react'
import { http, HttpResponse } from 'msw'
import type { Collection, CollectionLabel, CollectionMember, CollectionPlace, CollectionStatus } from '@trek/shared'
import { TranslationProvider } from '../../i18n'
import { useAuthStore } from '../../store/authStore'
import { useSettingsStore } from '../../store/settingsStore'
import { addListener, removeListener } from '../../api/websocket'
import { seedStore } from '../../../tests/helpers/store'
import { server } from '../../../tests/helpers/msw/server'
import { useCollections } from './useCollections'
const navigate = vi.fn()
let routeParams: { id?: string } = {}
vi.mock('react-router-dom', () => ({
useNavigate: () => navigate,
useParams: () => routeParams,
}))
// The fixture is handed out by the mocked store hook; tests mutate it and rerender.
const hoisted = vi.hoisted(() => ({ store: null as unknown }))
vi.mock('../../store/collectionStore', () => ({
ALL_SAVED: 'all',
useCollectionStore: () => hoisted.store,
}))
// ── Fixtures ─────────────────────────────────────────────────────────────────
function makeStore() {
return {
collections: [] as Collection[],
activeId: 'all' as number | 'all' | null,
places: [] as CollectionPlace[],
members: [] as CollectionMember[],
labels: [] as CollectionLabel[],
incomingInvites: [] as unknown[],
view: 'list' as 'list' | 'map',
statusFilter: 'all' as CollectionStatus | 'all',
categoryFilter: 'all' as number | 'all',
ratingFilter: 'all' as number | 'all',
labelFilter: [] as number[],
sortMode: 'default' as 'default' | 'name_asc',
search: '',
selectedPlaceId: null as number | null,
selectMode: false,
selectedIds: [] as number[],
loading: false,
placesLoading: false,
loadAll: vi.fn(async () => {}),
setActive: vi.fn(async (_id: number | 'all' | null) => {}),
refreshActive: vi.fn(async () => {}),
loadCollection: vi.fn(async (_id: number) => {}),
deleteCollection: vi.fn(async (_id: number) => {}),
setStatus: vi.fn(async (_id: number, _status: CollectionStatus) => {}),
updatePlace: vi.fn(async (_id: number, _body: Record<string, unknown>) => {}),
uploadPlaceImage: vi.fn(async (_id: number, _file: File) => {}),
ratePlace: vi.fn(async (_id: number, _rating: number | null) => {}),
deletePlace: vi.fn(async (_id: number) => {}),
deleteMany: vi.fn(async (_ids: number[]) => {}),
copyToTrip: vi.fn(async (_tripId: number, _ids: number[]) => ({ copied: 2, skipped: [] as { id: number; name: string }[] })),
clearSelection: vi.fn(() => {}),
moveToList: vi.fn(async (_ids: number[], _target: number) => {}),
duplicateToList: vi.fn(async (_ids: number[], _target: number) => {}),
setSelectedIds: vi.fn((_ids: number[]) => {}),
createLabel: vi.fn(async (_name: string, _color?: string) => {}),
updateLabel: vi.fn(async (_id: number, _body: Record<string, unknown>) => {}),
deleteLabel: vi.fn(async (_id: number) => {}),
assignLabels: vi.fn(async (_labelIds: number[], _placeIds: number[]) => {}),
acceptInvite: vi.fn(async (_id: number) => {}),
declineInvite: vi.fn(async (_id: number) => {}),
setView: vi.fn(() => {}),
setStatusFilter: vi.fn(() => {}),
setCategoryFilter: vi.fn(() => {}),
setRatingFilter: vi.fn(() => {}),
setLabelFilter: vi.fn(() => {}),
setSortMode: vi.fn(() => {}),
setSearch: vi.fn(() => {}),
setSelectedPlaceId: vi.fn((_id: number | null) => {}),
setSelectMode: vi.fn(() => {}),
toggleSelect: vi.fn(() => {}),
}
}
let store = makeStore()
function collection(over: Partial<Collection> & { id: number }): Collection {
return { owner_id: 1, name: `List ${over.id}`, is_owner: true, ...over } as unknown as Collection
}
function place(over: Partial<CollectionPlace> & { id: number }): CollectionPlace {
return { collection_id: 1, name: `Place ${over.id}`, status: 'idea', ...over } as unknown as CollectionPlace
}
// ── Environment stubs ────────────────────────────────────────────────────────
let wideMedia = false
let darkMedia = false
let mqChangeHandlers: Array<() => void> = []
function installMatchMedia() {
mqChangeHandlers = []
window.matchMedia = ((query: string) => ({
// A getter so flipping the flag mid-test is visible to the captured handler.
get matches() {
if (query.includes('min-width: 1024px')) return wideMedia
if (query.includes('prefers-color-scheme: dark')) return darkMedia
return false
},
media: query,
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: (_type: string, handler: () => void) => { mqChangeHandlers.push(handler) },
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})) as unknown as typeof window.matchMedia
}
const addToast = vi.fn((_message: string, _type?: string, _duration?: number) => 0)
function wrapper({ children }: { children: React.ReactNode }) {
return <TranslationProvider>{children}</TranslationProvider>
}
// Mount and let the initial categories request settle so no state lands after
// the test has finished.
async function setup() {
hoisted.store = store
const view = renderHook(() => useCollections(), { wrapper })
await waitFor(() => expect(view.result.current.categories).toHaveLength(2))
return view
}
/** The websocket handler the hook registered on its last render. */
function wsHandler(): (msg: { type: string; collectionId?: number }) => void {
const calls = vi.mocked(addListener).mock.calls
return calls[calls.length - 1][0] as unknown as (msg: { type: string; collectionId?: number }) => void
}
beforeEach(() => {
store = makeStore()
hoisted.store = store
routeParams = {}
wideMedia = false
darkMedia = false
navigate.mockClear()
addToast.mockClear()
vi.mocked(addListener).mockClear()
vi.mocked(removeListener).mockClear()
installMatchMedia()
window.__addToast = addToast as unknown as typeof window.__addToast
seedStore(useSettingsStore, { settings: { dark_mode: false } })
seedStore(useAuthStore, { user: { id: 7, username: 'me', email: 'me@example.com', role: 'user' } })
})
afterEach(() => {
vi.unstubAllGlobals()
vi.restoreAllMocks()
delete window.__addToast
})
describe('useCollections — mount', () => {
it('FE-PAGE-COLL-001: loads the lists and the central categories on mount', async () => {
const { result } = await setup()
expect(store.loadAll).toHaveBeenCalledTimes(1)
expect(result.current.categories).toHaveLength(2)
expect(result.current.language).toBe('en')
})
it('FE-PAGE-COLL-002: registers a websocket listener and drops it on unmount', async () => {
const { unmount } = await setup()
expect(addListener).toHaveBeenCalled()
const registered = vi.mocked(addListener).mock.calls[0][0]
unmount()
expect(removeListener).toHaveBeenCalledWith(registered)
})
it('FE-PAGE-COLL-003: a route without an id activates the All-saved union', async () => {
store.activeId = 5
await setup()
expect(store.setActive).toHaveBeenCalledWith('all')
})
it('FE-PAGE-COLL-004: /collections/:id activates that list', async () => {
routeParams = { id: '7' }
await setup()
expect(store.setActive).toHaveBeenCalledWith(7)
})
it('FE-PAGE-COLL-005: a non-numeric route id is ignored', async () => {
routeParams = { id: 'not-a-number' }
await setup()
expect(store.setActive).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-006: an already-active list is not re-activated', async () => {
routeParams = { id: '7' }
store.activeId = 7
await setup()
expect(store.setActive).not.toHaveBeenCalled()
})
})
describe('useCollections — categories request', () => {
it('FE-PAGE-COLL-082: a failing categories request leaves the list empty', async () => {
server.use(http.get('/api/categories', () => new HttpResponse(null, { status: 500 })))
hoisted.store = store
const { result } = renderHook(() => useCollections(), { wrapper })
await waitFor(() => expect(store.loadAll).toHaveBeenCalled())
expect(result.current.categories).toEqual([])
})
it('FE-PAGE-COLL-083: a payload without a categories array falls back to an empty list', async () => {
server.use(http.get('/api/categories', () => HttpResponse.json({})))
hoisted.store = store
const { result } = renderHook(() => useCollections(), { wrapper })
await waitFor(() => expect(store.loadAll).toHaveBeenCalled())
expect(result.current.categories).toEqual([])
})
})
describe('useCollections — appearance and breakpoint', () => {
it('FE-PAGE-COLL-007: an explicit dark_mode setting turns the dark flag on', async () => {
seedStore(useSettingsStore, { settings: { dark_mode: 'dark' } })
const { result } = await setup()
expect(result.current.dark).toBe(true)
})
it('FE-PAGE-COLL-008: dark_mode auto follows the OS colour scheme', async () => {
seedStore(useSettingsStore, { settings: { dark_mode: 'auto' } })
darkMedia = true
const { result } = await setup()
expect(result.current.dark).toBe(true)
})
it('FE-PAGE-COLL-009: dark_mode auto stays light when the OS prefers light', async () => {
seedStore(useSettingsStore, { settings: { dark_mode: 'auto' } })
darkMedia = false
const { result } = await setup()
expect(result.current.dark).toBe(false)
})
it('FE-PAGE-COLL-010: isWide tracks the 1024px media query and its change event', async () => {
const { result } = await setup()
expect(result.current.isWide).toBe(false)
wideMedia = true
act(() => { mqChangeHandlers.forEach(h => h()) })
expect(result.current.isWide).toBe(true)
})
})
describe('useCollections — active list and permissions', () => {
it('FE-PAGE-COLL-011: resolves the active collection from the id', async () => {
store.collections = [collection({ id: 1 }), collection({ id: 2, name: 'Japan' })]
store.activeId = 2
const { result } = await setup()
expect(result.current.activeCollection?.name).toBe('Japan')
expect(result.current.isAllSaved).toBe(false)
expect(result.current.isOwner).toBe(true)
expect(result.current.canShare).toBe(true)
})
it('FE-PAGE-COLL-012: the All-saved union has no collection and stays permissive', async () => {
store.activeId = 'all'
const { result } = await setup()
expect(result.current.activeCollection).toBeNull()
expect(result.current.isAllSaved).toBe(true)
expect(result.current.canEdit).toBe(true)
expect(result.current.canDelete).toBe(true)
expect(result.current.canShare).toBe(false)
})
it('FE-PAGE-COLL-013: an editor may edit but not delete', async () => {
store.collections = [collection({ id: 2, is_owner: false })]
store.activeId = 2
store.members = [{ user_id: 7, username: 'me', status: 'accepted', role: 'editor' } as unknown as CollectionMember]
const { result } = await setup()
expect(result.current.myRole).toBe('editor')
expect(result.current.canEdit).toBe(true)
expect(result.current.canDelete).toBe(false)
})
it('FE-PAGE-COLL-014: an admin may edit and delete', async () => {
store.collections = [collection({ id: 2, is_owner: false })]
store.activeId = 2
store.members = [{ user_id: 7, username: 'me', status: 'accepted', role: 'admin' } as unknown as CollectionMember]
const { result } = await setup()
expect(result.current.canEdit).toBe(true)
expect(result.current.canDelete).toBe(true)
})
it('FE-PAGE-COLL-015: a viewer may neither edit nor delete', async () => {
store.collections = [collection({ id: 2, is_owner: false })]
store.activeId = 2
store.members = [{ user_id: 7, username: 'me', status: 'accepted', role: 'viewer' } as unknown as CollectionMember]
const { result } = await setup()
expect(result.current.myRole).toBe('viewer')
expect(result.current.canEdit).toBe(false)
expect(result.current.canDelete).toBe(false)
})
it('FE-PAGE-COLL-016: a non-member has no role at all', async () => {
store.collections = [collection({ id: 2, is_owner: false })]
store.activeId = 2
store.members = [{ user_id: 99, username: 'other', status: 'accepted', role: 'editor' } as unknown as CollectionMember]
const { result } = await setup()
expect(result.current.myRole).toBeNull()
expect(result.current.canEdit).toBe(false)
})
it('FE-PAGE-COLL-017: the share badge counts everyone but the owner', async () => {
store.collections = [collection({ id: 2 })]
store.activeId = 2
store.members = [
{ user_id: 1, username: 'owner', status: 'accepted', is_owner: true } as unknown as CollectionMember,
{ user_id: 7, username: 'me', status: 'accepted', role: 'editor' } as unknown as CollectionMember,
{ user_id: 8, username: 'pending', status: 'pending', role: 'viewer' } as unknown as CollectionMember,
]
const { result } = await setup()
expect(result.current.shareMemberCount).toBe(2)
})
it('FE-PAGE-COLL-018: splits the rail into owned and shared lists', async () => {
store.collections = [collection({ id: 1 }), collection({ id: 2, is_owner: false }), collection({ id: 3, is_owner: undefined })]
const { result } = await setup()
expect(result.current.ownedLists.map(c => c.id)).toEqual([1, 3])
expect(result.current.sharedLists.map(c => c.id)).toEqual([2])
})
it('FE-PAGE-COLL-019: closes the share modal when the active list changes', async () => {
store.collections = [collection({ id: 1 }), collection({ id: 2 })]
store.activeId = 1
const { result, rerender } = await setup()
act(() => result.current.setShowShare(true))
expect(result.current.showShare).toBe(true)
store.activeId = 2
rerender()
expect(result.current.showShare).toBe(false)
})
})
describe('useCollections — derived place lists', () => {
beforeEach(() => {
store.activeId = 1
store.collections = [collection({ id: 1 })]
store.places = [
place({ id: 1, name: 'Bar', status: 'want', lat: 10, lng: 20, category_id: 3, category: { id: 3, name: 'Food', color: '#f00', icon: 'utensils' } as unknown as CollectionPlace['category'], label_ids: [50], sort_order: 1 }),
place({ id: 2, name: 'Alpha', status: 'idea', label_ids: [51], sort_order: 0 }),
place({ id: 3, name: 'Zoo', status: 'visited', lat: 1, lng: 2, sort_order: 2 }),
]
store.labels = [
{ id: 50, collection_id: 1, name: 'Food', color: '#f00' },
{ id: 51, collection_id: 1, name: 'Culture', color: null },
]
})
it('FE-PAGE-COLL-020: visiblePlaces keeps the saved order by default', async () => {
const { result } = await setup()
expect(result.current.visiblePlaces.map(p => p.id)).toEqual([2, 1, 3])
expect(result.current.counts).toEqual({ all: 3, idea: 1, want: 1, visited: 1 })
expect(result.current.mappable.map(p => p.id)).toEqual([1, 3])
})
it('FE-PAGE-COLL-021: the alphabetical sort mode reorders by name', async () => {
store.sortMode = 'name_asc'
const { result } = await setup()
expect(result.current.visiblePlaces.map(p => p.name)).toEqual(['Alpha', 'Bar', 'Zoo'])
})
it('FE-PAGE-COLL-022: status, search and category filters narrow the list', async () => {
store.statusFilter = 'want'
const { result, rerender } = await setup()
expect(result.current.visiblePlaces.map(p => p.id)).toEqual([1])
store.statusFilter = 'all'
store.search = 'zo'
rerender()
expect(result.current.visiblePlaces.map(p => p.id)).toEqual([3])
store.search = ''
store.categoryFilter = 3
rerender()
expect(result.current.visiblePlaces.map(p => p.id)).toEqual([1])
})
it('FE-PAGE-COLL-023: the label filter applies on a real list', async () => {
store.labelFilter = [51]
const { result } = await setup()
expect(result.current.visiblePlaces.map(p => p.id)).toEqual([2])
})
it('FE-PAGE-COLL-024: the label filter is ignored on the All-saved union', async () => {
store.activeId = 'all'
store.labelFilter = [51]
const { result } = await setup()
expect(result.current.visiblePlaces).toHaveLength(3)
})
it('FE-PAGE-COLL-025: category and label options carry their counts', async () => {
const { result } = await setup()
expect(result.current.categoryOptions).toEqual([{ id: 3, name: 'Food', color: '#f00', icon: 'utensils', count: 1 }])
expect(result.current.labelOptions.map(l => [l.id, l.count])).toEqual([[50, 1], [51, 1]])
})
it('FE-PAGE-COLL-026: allVisibleSelected only once every visible place is selected', async () => {
store.selectedIds = [1, 2]
const { result, rerender } = await setup()
expect(result.current.allVisibleSelected).toBe(false)
store.selectedIds = [1, 2, 3]
rerender()
expect(result.current.allVisibleSelected).toBe(true)
})
it('FE-PAGE-COLL-027: handleSelectAll selects every visible place, then clears', async () => {
const { result, rerender } = await setup()
act(() => result.current.handleSelectAll())
expect(store.setSelectedIds).toHaveBeenCalledWith([2, 1, 3])
store.selectedIds = [1, 2, 3]
rerender()
act(() => result.current.handleSelectAll())
expect(store.setSelectedIds).toHaveBeenLastCalledWith([])
})
it('FE-PAGE-COLL-028: the detail place is shimmed with a trip id', async () => {
store.places = [place({ id: 4, name: 'Museum', source_trip_id: 12, category: { id: 3, name: 'Food' } as unknown as CollectionPlace['category'] })]
store.selectedPlaceId = 4
const { result } = await setup()
expect(result.current.selectedPlace?.name).toBe('Museum')
expect(result.current.detailPlace?.trip_id).toBe(12)
expect(result.current.detailCategories).toHaveLength(1)
})
it('FE-PAGE-COLL-029: a place without a source trip falls back to trip id 0 and no category chip', async () => {
store.places = [place({ id: 4, name: 'Museum' })]
store.selectedPlaceId = 4
const { result } = await setup()
expect(result.current.detailPlace?.trip_id).toBe(0)
expect(result.current.detailCategories).toEqual([])
})
it('FE-PAGE-COLL-030: an unknown selection resolves to no detail place', async () => {
store.selectedPlaceId = 999
const { result } = await setup()
expect(result.current.selectedPlace).toBeNull()
expect(result.current.detailPlace).toBeNull()
})
})
describe('useCollections — list handlers', () => {
it('FE-PAGE-COLL-031: selecting a list navigates to it and closes the mobile rail', async () => {
const { result } = await setup()
act(() => result.current.setMobileRailOpen(true))
expect(result.current.mobileRailOpen).toBe(true)
act(() => result.current.handleSelectList(4))
expect(navigate).toHaveBeenCalledWith('/collections/4')
expect(result.current.mobileRailOpen).toBe(false)
})
it('FE-PAGE-COLL-032: the All-saved entry and a null id both go to the index route', async () => {
const { result } = await setup()
act(() => result.current.handleSelectList('all'))
expect(navigate).toHaveBeenLastCalledWith('/collections')
act(() => result.current.handleSelectList(null))
expect(navigate).toHaveBeenLastCalledWith('/collections')
})
it('FE-PAGE-COLL-033: a freshly created list is opened', async () => {
const { result } = await setup()
act(() => result.current.handleEditorCreated(11))
expect(navigate).toHaveBeenCalledWith('/collections/11')
})
it('FE-PAGE-COLL-034: adding a place refreshes the active list', async () => {
const { result } = await setup()
act(() => result.current.handlePlaceAdded())
expect(store.refreshActive).toHaveBeenCalledTimes(1)
})
it('FE-PAGE-COLL-035: deleting without a pending confirmation does nothing', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleDeleteList() })
expect(store.deleteCollection).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-036: confirming the delete removes the list and bounces off it', async () => {
store.activeId = 3
const { result } = await setup()
act(() => result.current.setConfirmDeleteList(3))
await act(async () => { await result.current.handleDeleteList() })
expect(store.deleteCollection).toHaveBeenCalledWith(3)
expect(navigate).toHaveBeenCalledWith('/collections')
expect(result.current.confirmDeleteList).toBeNull()
})
it('FE-PAGE-COLL-037: deleting a list you are not on does not navigate', async () => {
store.activeId = 9
const { result } = await setup()
act(() => result.current.setConfirmDeleteList(3))
await act(async () => { await result.current.handleDeleteList() })
expect(store.deleteCollection).toHaveBeenCalledWith(3)
expect(navigate).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-038: a failing delete is surfaced as a toast', async () => {
store.deleteCollection.mockRejectedValueOnce(new Error('list is locked'))
const { result } = await setup()
act(() => result.current.setConfirmDeleteList(3))
await act(async () => { await result.current.handleDeleteList() })
expect(addToast).toHaveBeenCalledWith('list is locked', 'error', undefined)
})
})
describe('useCollections — place handlers', () => {
it('FE-PAGE-COLL-039: status changes forward to the store', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleStatusChange(5, 'visited') })
expect(store.setStatus).toHaveBeenCalledWith(5, 'visited')
})
it('FE-PAGE-COLL-040: a failing status change toasts the error', async () => {
store.setStatus.mockRejectedValueOnce(new Error('offline'))
const { result } = await setup()
await act(async () => { await result.current.handleStatusChange(5, 'visited') })
expect(addToast).toHaveBeenCalledWith('offline', 'error', undefined)
})
it('FE-PAGE-COLL-041: deleting a place forwards, and failures toast', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleDeletePlace(5) })
expect(store.deletePlace).toHaveBeenCalledWith(5)
store.deletePlace.mockRejectedValueOnce(new Error('nope'))
await act(async () => { await result.current.handleDeletePlace(5) })
expect(addToast).toHaveBeenCalledWith('nope', 'error', undefined)
})
it('FE-PAGE-COLL-042: rating a place forwards, and failures toast', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleRatePlace(5, 4) })
expect(store.ratePlace).toHaveBeenCalledWith(5, 4)
store.ratePlace.mockRejectedValueOnce(new Error('rate limited'))
await act(async () => { await result.current.handleRatePlace(5, null) })
expect(addToast).toHaveBeenCalledWith('rate limited', 'error', undefined)
})
it('FE-PAGE-COLL-043: bulk delete no-ops on an empty selection', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleDeleteSelected() })
expect(store.deleteMany).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-044: bulk delete forwards the selection and toasts failures', async () => {
store.selectedIds = [1, 2]
const { result } = await setup()
await act(async () => { await result.current.handleDeleteSelected() })
expect(store.deleteMany).toHaveBeenCalledWith([1, 2])
store.deleteMany.mockRejectedValueOnce(new Error('denied'))
await act(async () => { await result.current.handleDeleteSelected() })
expect(addToast).toHaveBeenCalledWith('denied', 'error', undefined)
})
})
describe('useCollections — move and duplicate', () => {
it('FE-PAGE-COLL-045: move and duplicate no-op on an empty selection', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleMoveToList(9) })
await act(async () => { await result.current.handleDuplicateToList(9) })
expect(store.moveToList).not.toHaveBeenCalled()
expect(store.duplicateToList).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-046: a successful move closes the picker and confirms with a toast', async () => {
store.selectedIds = [1, 2]
const { result } = await setup()
act(() => result.current.setListPickerMode('move'))
await act(async () => { await result.current.handleMoveToList(9) })
expect(store.moveToList).toHaveBeenCalledWith([1, 2], 9)
expect(result.current.listPickerMode).toBeNull()
expect(addToast).toHaveBeenCalledWith(expect.stringContaining('2'), 'success', undefined)
})
it('FE-PAGE-COLL-047: a failing move keeps the picker open and toasts', async () => {
store.selectedIds = [1]
store.moveToList.mockRejectedValueOnce(new Error('target is read-only'))
const { result } = await setup()
act(() => result.current.setListPickerMode('move'))
await act(async () => { await result.current.handleMoveToList(9) })
expect(result.current.listPickerMode).toBe('move')
expect(addToast).toHaveBeenCalledWith('target is read-only', 'error', undefined)
})
it('FE-PAGE-COLL-048: a successful duplicate closes the picker', async () => {
store.selectedIds = [3]
const { result } = await setup()
act(() => result.current.setListPickerMode('copy'))
await act(async () => { await result.current.handleDuplicateToList(9) })
expect(store.duplicateToList).toHaveBeenCalledWith([3], 9)
expect(result.current.listPickerMode).toBeNull()
})
it('FE-PAGE-COLL-049: a failing duplicate toasts', async () => {
store.selectedIds = [3]
store.duplicateToList.mockRejectedValueOnce(new Error('quota'))
const { result } = await setup()
await act(async () => { await result.current.handleDuplicateToList(9) })
expect(addToast).toHaveBeenCalledWith('quota', 'error', undefined)
})
})
describe('useCollections — labels', () => {
it('FE-PAGE-COLL-050: create, update and delete forward to the store', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleCreateLabel('Food', '#f00') })
await act(async () => { await result.current.handleUpdateLabel(3, { name: 'Drinks' }) })
await act(async () => { await result.current.handleDeleteLabel(3) })
expect(store.createLabel).toHaveBeenCalledWith('Food', '#f00')
expect(store.updateLabel).toHaveBeenCalledWith(3, { name: 'Drinks' })
expect(store.deleteLabel).toHaveBeenCalledWith(3)
})
it('FE-PAGE-COLL-051: each label mutation surfaces its error', async () => {
store.createLabel.mockRejectedValueOnce(new Error('dup name'))
store.updateLabel.mockRejectedValueOnce(new Error('gone'))
store.deleteLabel.mockRejectedValueOnce(new Error('in use'))
const { result } = await setup()
await act(async () => { await result.current.handleCreateLabel('Food') })
expect(addToast).toHaveBeenLastCalledWith('dup name', 'error', undefined)
await act(async () => { await result.current.handleUpdateLabel(3, { color: '#000' }) })
expect(addToast).toHaveBeenLastCalledWith('gone', 'error', undefined)
await act(async () => { await result.current.handleDeleteLabel(3) })
expect(addToast).toHaveBeenLastCalledWith('in use', 'error', undefined)
})
it('FE-PAGE-COLL-052: bulk assign needs both a selection and a label', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleBulkAssignLabels([1]) })
expect(store.assignLabels).not.toHaveBeenCalled()
store.selectedIds = [4]
await act(async () => { await result.current.handleBulkAssignLabels([]) })
expect(store.assignLabels).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-053: a successful bulk assign closes the picker', async () => {
store.selectedIds = [4, 5]
const { result } = await setup()
act(() => result.current.setLabelPickerOpen(true))
await act(async () => { await result.current.handleBulkAssignLabels([1, 2]) })
expect(store.assignLabels).toHaveBeenCalledWith([1, 2], [4, 5])
expect(result.current.labelPickerOpen).toBe(false)
expect(addToast).toHaveBeenCalledWith(expect.stringContaining('2'), 'success', undefined)
})
it('FE-PAGE-COLL-054: a failing bulk assign leaves the picker open', async () => {
store.selectedIds = [4]
store.assignLabels.mockRejectedValueOnce(new Error('label missing'))
const { result } = await setup()
act(() => result.current.setLabelPickerOpen(true))
await act(async () => { await result.current.handleBulkAssignLabels([1]) })
expect(result.current.labelPickerOpen).toBe(true)
expect(addToast).toHaveBeenCalledWith('label missing', 'error', undefined)
})
it('FE-PAGE-COLL-055: assigning labels to one place patches that place', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleAssignPlaceLabels(8, [1, 2]) })
expect(store.updatePlace).toHaveBeenCalledWith(8, { label_ids: [1, 2] })
store.updatePlace.mockRejectedValueOnce(new Error('conflict'))
await act(async () => { await result.current.handleAssignPlaceLabels(8, []) })
expect(addToast).toHaveBeenCalledWith('conflict', 'error', undefined)
})
})
describe('useCollections — invites and leaving', () => {
it('FE-PAGE-COLL-056: accepting an invite opens the list', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleAcceptInvite(12) })
expect(store.acceptInvite).toHaveBeenCalledWith(12)
expect(navigate).toHaveBeenCalledWith('/collections/12')
})
it('FE-PAGE-COLL-057: a failing accept toasts and does not navigate', async () => {
store.acceptInvite.mockRejectedValueOnce(new Error('invite expired'))
const { result } = await setup()
await act(async () => { await result.current.handleAcceptInvite(12) })
expect(navigate).not.toHaveBeenCalled()
expect(addToast).toHaveBeenCalledWith('invite expired', 'error', undefined)
})
it('FE-PAGE-COLL-058: declining forwards, and failures toast', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleDeclineInvite(12) })
expect(store.declineInvite).toHaveBeenCalledWith(12)
store.declineInvite.mockRejectedValueOnce(new Error('already gone'))
await act(async () => { await result.current.handleDeclineInvite(12) })
expect(addToast).toHaveBeenCalledWith('already gone', 'error', undefined)
})
it('FE-PAGE-COLL-059: leaving a shared list closes the share modal and bounces to the rail', async () => {
const { result } = await setup()
act(() => result.current.setShowShare(true))
act(() => result.current.handleAfterLeave())
expect(result.current.showShare).toBe(false)
expect(navigate).toHaveBeenCalledWith('/collections')
})
})
describe('useCollections — detail panel and copy to trip', () => {
beforeEach(() => {
store.places = [place({ id: 4 }), place({ id: 5 })]
})
it('FE-PAGE-COLL-060: closing the detail clears the selection', async () => {
const { result } = await setup()
act(() => result.current.handleCloseDetail())
expect(store.setSelectedPlaceId).toHaveBeenCalledWith(null)
})
it('FE-PAGE-COLL-061: the detail status button no-ops without a selected place', async () => {
const { result } = await setup()
act(() => result.current.handleDetailStatus('want'))
expect(store.setStatus).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-062: the detail status button sets the status of the open place', async () => {
store.selectedPlaceId = 4
const { result } = await setup()
await act(async () => { result.current.handleDetailStatus('want') })
expect(store.setStatus).toHaveBeenCalledWith(4, 'want')
})
it('FE-PAGE-COLL-063: removing from the detail deletes and closes it', async () => {
store.selectedPlaceId = 4
const { result } = await setup()
await act(async () => { await result.current.handleDetailRemove() })
expect(store.deletePlace).toHaveBeenCalledWith(4)
expect(store.setSelectedPlaceId).toHaveBeenCalledWith(null)
})
it('FE-PAGE-COLL-064: removing without a selected place does nothing', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleDetailRemove() })
expect(store.deletePlace).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-065: copy-to-trip opens for the place in the detail sheet', async () => {
store.selectedPlaceId = 5
const { result } = await setup()
act(() => result.current.openCopyForSelectedPlace())
expect(result.current.copyIds).toEqual([5])
act(() => result.current.closeCopy())
expect(result.current.copyIds).toBeNull()
})
it('FE-PAGE-COLL-066: copy-to-trip stays closed without a selected place', async () => {
const { result } = await setup()
act(() => result.current.openCopyForSelectedPlace())
expect(result.current.copyIds).toBeNull()
})
it('FE-PAGE-COLL-067: copy-to-trip opens for the whole select-mode set', async () => {
store.selectedIds = [4, 5]
const { result } = await setup()
act(() => result.current.openCopyForSelection())
expect(result.current.copyIds).toEqual([4, 5])
})
it('FE-PAGE-COLL-068: copy-to-trip stays closed for an empty selection', async () => {
const { result } = await setup()
act(() => result.current.openCopyForSelection())
expect(result.current.copyIds).toBeNull()
})
it('FE-PAGE-COLL-069: copying returns the store result and clears select mode', async () => {
store.selectedIds = [4, 5]
store.selectMode = true
const { result } = await setup()
act(() => result.current.openCopyForSelection())
let res: { copied: number } | undefined
await act(async () => { res = await result.current.handleCopyToTrip(20) })
expect(store.copyToTrip).toHaveBeenCalledWith(20, [4, 5])
expect(res?.copied).toBe(2)
expect(store.clearSelection).toHaveBeenCalled()
})
it('FE-PAGE-COLL-070: copying without an open modal sends an empty id list', async () => {
const { result } = await setup()
await act(async () => { await result.current.handleCopyToTrip(20) })
expect(store.copyToTrip).toHaveBeenCalledWith(20, [])
expect(store.clearSelection).not.toHaveBeenCalled()
})
})
describe('useCollections — websocket sync', () => {
it('FE-PAGE-COLL-071: ignores messages from other domains', async () => {
await setup()
store.loadAll.mockClear()
act(() => wsHandler()({ type: 'trip:updated' }))
expect(store.loadAll).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-072: a deleted active list bounces to the rail', async () => {
store.activeId = 4
await setup()
store.loadAll.mockClear()
act(() => wsHandler()({ type: 'collections:deleted', collectionId: 4 }))
expect(navigate).toHaveBeenCalledWith('/collections')
expect(store.loadAll).toHaveBeenCalledTimes(1)
})
it('FE-PAGE-COLL-073: being removed from another list only refreshes the rail', async () => {
store.activeId = 4
await setup()
store.loadAll.mockClear()
act(() => wsHandler()({ type: 'collections:removed', collectionId: 9 }))
expect(navigate).not.toHaveBeenCalled()
expect(store.loadAll).toHaveBeenCalledTimes(1)
expect(store.loadCollection).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-074: an incoming invite is announced', async () => {
await setup()
act(() => wsHandler()({ type: 'collections:invite' }))
expect(addToast).toHaveBeenCalledWith(expect.any(String), 'info', undefined)
})
it('FE-PAGE-COLL-075: an update reloads the active list without dropping the selection', async () => {
store.activeId = 4
await setup()
store.loadAll.mockClear()
// The route sync already activated the union on mount; only the WS effect counts here.
store.setActive.mockClear()
act(() => wsHandler()({ type: 'collections:updated', collectionId: 4 }))
expect(store.loadAll).toHaveBeenCalledTimes(1)
expect(store.loadCollection).toHaveBeenCalledWith(4)
expect(store.setActive).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-084: an update with no active list only refreshes the rail', async () => {
routeParams = { id: 'nope' }
store.activeId = null
await setup()
store.loadAll.mockClear()
act(() => wsHandler()({ type: 'collections:left' }))
expect(store.loadAll).toHaveBeenCalledTimes(1)
expect(store.loadCollection).not.toHaveBeenCalled()
expect(store.setActive).not.toHaveBeenCalled()
})
it('FE-PAGE-COLL-076: an update on the All-saved union re-unions the lists', async () => {
store.activeId = 'all'
await setup()
act(() => wsHandler()({ type: 'collections:accepted' }))
expect(store.setActive).toHaveBeenCalledWith('all')
expect(store.loadCollection).not.toHaveBeenCalled()
})
})
describe('useCollections — map relayout nudge', () => {
it('FE-PAGE-COLL-077: toggling the view on a wide layout pumps resize events until the transition ends', async () => {
wideMedia = true
const frames: FrameRequestCallback[] = []
const cancel = vi.fn()
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { frames.push(cb); return frames.length })
vi.stubGlobal('cancelAnimationFrame', cancel)
const now = vi.spyOn(performance, 'now').mockReturnValue(0)
const onResize = vi.fn()
window.addEventListener('resize', onResize)
const { rerender, unmount } = await setup()
expect(frames).toHaveLength(0)
store.view = 'map'
rerender()
expect(frames).toHaveLength(1)
act(() => { frames[0](0) })
expect(onResize).toHaveBeenCalledTimes(1)
expect(frames).toHaveLength(2)
// Past the 440ms transition window the loop stops scheduling.
now.mockReturnValue(1000)
act(() => { frames[1](0) })
expect(onResize).toHaveBeenCalledTimes(2)
expect(frames).toHaveLength(2)
unmount()
expect(cancel).toHaveBeenCalled()
window.removeEventListener('resize', onResize)
})
it('FE-PAGE-COLL-078: a narrow layout never schedules the nudge', async () => {
wideMedia = false
const frames: FrameRequestCallback[] = []
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { frames.push(cb); return frames.length })
vi.stubGlobal('cancelAnimationFrame', vi.fn())
const { rerender } = await setup()
store.view = 'map'
rerender()
expect(frames).toHaveLength(0)
})
})
describe('useCollections — local UI state', () => {
it('FE-PAGE-COLL-079: the list editor target opens for create and for an existing list', async () => {
const target = collection({ id: 3, name: 'Rome' })
const { result } = await setup()
act(() => result.current.setEditorTarget('new'))
expect(result.current.editorTarget).toBe('new')
act(() => result.current.setEditorTarget(target))
expect(result.current.editorTarget).toEqual(target)
act(() => result.current.setEditorTarget(null))
expect(result.current.editorTarget).toBeNull()
})
it('FE-PAGE-COLL-080: the add-place and label-manager modals toggle', async () => {
const { result } = await setup()
act(() => result.current.setShowAddPlace(true))
expect(result.current.showAddPlace).toBe(true)
act(() => result.current.setShowLabelManager(true))
expect(result.current.showLabelManager).toBe(true)
})
it('FE-PAGE-COLL-081: store setters are handed through untouched', async () => {
const { result } = await setup()
expect(result.current.setView).toBe(store.setView)
expect(result.current.setSortMode).toBe(store.setSortMode)
expect(result.current.setRatingFilter).toBe(store.setRatingFilter)
expect(result.current.toggleSelect).toBe(store.toggleSelect)
expect(result.current.uploadPlaceImage).toBe(store.uploadPlaceImage)
})
})
@@ -0,0 +1,97 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { daysUntil, getTripStatus, sortTrips, MS_PER_DAY, type DashboardTrip } from './dashboardModel';
// FE-HOOK-DASHMODEL-001 onwards
const trip = (over: Partial<DashboardTrip>): DashboardTrip =>
({ id: 1, title: 't', ...over }) as unknown as DashboardTrip;
const offset = (days: number): string => {
const d = new Date('2026-07-15T12:00:00Z');
d.setUTCDate(d.getUTCDate() + days);
return d.toISOString().split('T')[0];
};
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-07-15T12:00:00Z'));
});
afterEach(() => {
vi.useRealTimers();
});
describe('daysUntil', () => {
it('FE-HOOK-DASHMODEL-001: has no answer without a date', () => {
expect(daysUntil(null)).toBeNull();
expect(daysUntil(undefined)).toBeNull();
});
it('FE-HOOK-DASHMODEL-002: counts forwards and backwards from today', () => {
expect(daysUntil(offset(0))).toBe(0);
expect(daysUntil(offset(5))).toBe(5);
expect(daysUntil(offset(-3))).toBe(-3);
});
});
describe('getTripStatus', () => {
it('FE-HOOK-DASHMODEL-003: a date range around today is ongoing', () => {
expect(getTripStatus(trip({ start_date: offset(-2), end_date: offset(2) }))).toBe('ongoing');
});
it('FE-HOOK-DASHMODEL-004: a trip without a start date has no status', () => {
expect(getTripStatus(trip({ start_date: null, end_date: null }))).toBeNull();
});
it.each([
[0, 'today'],
[1, 'tomorrow'],
[9, 'future'],
[-9, 'past'],
] as Array<[number, string]>)('FE-HOOK-DASHMODEL-005: a start in %s days is %s', (days, status) => {
// No end date, so the "ongoing" rule cannot swallow the start-relative states.
expect(getTripStatus(trip({ start_date: offset(days), end_date: null }))).toBe(status);
});
it('FE-HOOK-DASHMODEL-010: a finished date range is past', () => {
expect(getTripStatus(trip({ start_date: offset(-9), end_date: offset(-8) }))).toBe('past');
});
});
describe('sortTrips', () => {
it('FE-HOOK-DASHMODEL-006: running first, then upcoming ascending, then finished descending', () => {
const sorted = sortTrips([
trip({ id: 1, start_date: offset(-40), end_date: offset(-30) }),
trip({ id: 2, start_date: offset(20), end_date: offset(25) }),
trip({ id: 3, start_date: offset(-1), end_date: offset(3) }),
trip({ id: 4, start_date: offset(5), end_date: offset(8) }),
trip({ id: 5, start_date: offset(-10), end_date: offset(-8) }),
]);
expect(sorted.map(t => t.id)).toEqual([3, 4, 2, 5, 1]);
});
it('FE-HOOK-DASHMODEL-007: leaves the input array untouched', () => {
const input = [trip({ id: 1, start_date: offset(10) }), trip({ id: 2, start_date: offset(1) })];
const sorted = sortTrips(input);
expect(input.map(t => t.id)).toEqual([1, 2]);
expect(sorted.map(t => t.id)).toEqual([2, 1]);
});
it('FE-HOOK-DASHMODEL-008: dateless trips rank last', () => {
const sorted = sortTrips([
trip({ id: 1, start_date: null, end_date: null }),
trip({ id: 2, start_date: offset(4), end_date: offset(6) }),
]);
expect(sorted.map(t => t.id)).toEqual([2, 1]);
});
});
describe('MS_PER_DAY', () => {
it('FE-HOOK-DASHMODEL-009: is one day in milliseconds', () => {
expect(MS_PER_DAY).toBe(24 * 60 * 60 * 1000);
});
});
@@ -0,0 +1,325 @@
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { renderHook, act, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildUser, buildTrip } from '../../../tests/helpers/factories';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAuthStore } from '../../store/authStore';
import { useDashboard } from './useDashboard';
import type { DashboardTrip } from './dashboardModel';
// FE-HOOK-DASH-001 onwards
const PARIS = buildTrip({ id: 101, title: 'Paris Adventure', start_date: '2026-07-01', end_date: '2026-07-10' });
const TOKYO = buildTrip({ id: 102, title: 'Tokyo Trip', start_date: '2027-09-01', end_date: '2027-09-15' });
const ROME = buildTrip({ id: 103, title: 'Old Rome', start_date: '2024-01-01', end_date: '2024-01-07', is_archived: 1 });
let toastCalls: Array<[string, string | undefined]>;
function tripsHandler(active: DashboardTrip[], archived: DashboardTrip[] = []) {
server.use(
http.get('/api/trips', ({ request }) => {
const url = new URL(request.url);
return HttpResponse.json({ trips: url.searchParams.get('archived') ? archived : active });
}),
);
}
function wrapper({ children }: { children: React.ReactNode }) {
return (
<MemoryRouter initialEntries={['/dashboard']}>
<TranslationProvider>{children}</TranslationProvider>
</MemoryRouter>
);
}
function createWrapper(entry: string) {
return function Wrapper({ children }: { children: React.ReactNode }) {
return (
<MemoryRouter initialEntries={[entry]}>
<TranslationProvider>{children}</TranslationProvider>
</MemoryRouter>
);
};
}
async function mountLoaded(entry = '/dashboard') {
const view = renderHook(() => useDashboard(), { wrapper: entry === '/dashboard' ? wrapper : createWrapper(entry) });
await waitFor(() => expect(view.result.current.isLoading).toBe(false));
return view;
}
beforeEach(() => {
resetAllStores();
seedStore(useAuthStore, { isAuthenticated: true, user: buildUser() });
toastCalls = [];
window.__addToast = ((message: string, type?: string) => {
toastCalls.push([message, type]);
return 1;
}) as unknown as typeof window.__addToast;
tripsHandler([PARIS, TOKYO], [ROME]);
server.use(
http.get('/api/auth/travel-stats', () => HttpResponse.json({ totalTrips: 2, countries: ['fr'] })),
http.get('/api/reservations/upcoming', () =>
HttpResponse.json({ reservations: [{ id: 5, trip_id: 101, title: 'Louvre', type: 'ticket' }] })),
);
});
afterEach(() => {
delete window.__addToast;
});
describe('useDashboard', () => {
it('FE-HOOK-DASH-001: loads trips, stats and the upcoming reservations', async () => {
const { result } = await mountLoaded();
expect(result.current.spotlight?.title).toBe('Tokyo Trip');
expect(result.current.loadError).toBe(false);
await waitFor(() => expect(result.current.stats?.totalTrips).toBe(2));
await waitFor(() => expect(result.current.upcoming).toHaveLength(1));
});
it('FE-HOOK-DASH-002: the planned filter drops finished trips, completed keeps only them', async () => {
const { result } = await mountLoaded();
// Tokyo is the spotlight and therefore not repeated in the grid.
expect(result.current.gridTrips.map(t => t.title)).toEqual([]);
act(() => result.current.setTripFilter('completed'));
expect(result.current.gridTrips.map(t => t.title)).toEqual(['Paris Adventure']);
act(() => result.current.setTripFilter('archive'));
expect(result.current.gridTrips.map(t => t.title)).toEqual(['Old Rome']);
});
it('FE-HOOK-DASH-003: ?create=1 opens the form and clears the query', async () => {
const { result } = await mountLoaded('/dashboard?create=1');
await waitFor(() => expect(result.current.showForm).toBe(true));
});
it('FE-HOOK-DASH-004: a failing trip load raises the error banner and toasts', async () => {
server.use(http.get('/api/trips', () => HttpResponse.json({ error: 'boom' }, { status: 500 })));
const { result } = await mountLoaded();
expect(result.current.loadError).toBe(true);
expect(toastCalls).toContainEqual(['Failed to load trips', 'error']);
});
it('FE-HOOK-DASH-005: retrying after recovery clears the banner', async () => {
server.use(http.get('/api/trips', () => HttpResponse.json({ error: 'boom' }, { status: 500 })));
const { result } = await mountLoaded();
expect(result.current.loadError).toBe(true);
tripsHandler([PARIS, TOKYO], [ROME]);
act(() => { result.current.retryLoad(); });
await waitFor(() => expect(result.current.loadError).toBe(false));
expect(result.current.spotlight?.title).toBe('Tokyo Trip');
});
it('FE-HOOK-DASH-006: an unhealthy auth check also counts as a load error', async () => {
const { result } = await mountLoaded();
act(() => { useAuthStore.setState({ authCheckFailed: true }); });
expect(result.current.loadError).toBe(true);
});
it('FE-HOOK-DASH-007: creating a trip prepends it and returns the payload', async () => {
const created = buildTrip({ id: 200, title: 'Iceland', start_date: '2027-12-01', end_date: '2027-12-05' });
server.use(http.post('/api/trips', () => HttpResponse.json({ trip: created })));
const { result } = await mountLoaded();
let payload: unknown;
await act(async () => { payload = await result.current.handleCreate({ title: 'Iceland' }); });
expect(payload).toEqual({ trip: created });
expect(toastCalls).toContainEqual(['Trip created successfully!', 'success']);
act(() => result.current.setTripFilter('planned'));
expect(result.current.gridTrips.some(t => t.title === 'Iceland')).toBe(true);
});
it('FE-HOOK-DASH-008: a rejected create surfaces the API message', async () => {
server.use(http.post('/api/trips', () => HttpResponse.json({ error: 'Title taken' }, { status: 400 })));
const { result } = await mountLoaded();
await expect(result.current.handleCreate({ title: 'Iceland' })).rejects.toThrow('Title taken');
});
it('FE-HOOK-DASH-009: updating replaces the edited trip', async () => {
server.use(http.put('/api/trips/:id', () =>
HttpResponse.json({ trip: { ...PARIS, title: 'Paris Reloaded' } })));
const { result } = await mountLoaded();
act(() => { result.current.setEditingTrip(PARIS); });
await act(async () => { await result.current.handleUpdate({ title: 'Paris Reloaded' }); });
act(() => result.current.setTripFilter('completed'));
expect(result.current.gridTrips.map(t => t.title)).toEqual(['Paris Reloaded']);
expect(toastCalls).toContainEqual(['Trip updated!', 'success']);
});
it('FE-HOOK-DASH-010: updating without an edited trip is a no-op', async () => {
const { result } = await mountLoaded();
await act(async () => { await result.current.handleUpdate({ title: 'nope' }); });
expect(toastCalls).toEqual([]);
});
it('FE-HOOK-DASH-011: a rejected update surfaces the API message', async () => {
server.use(http.put('/api/trips/:id', () => HttpResponse.json({ error: 'Locked' }, { status: 409 })));
const { result } = await mountLoaded();
act(() => { result.current.setEditingTrip(PARIS); });
await expect(result.current.handleUpdate({ title: 'x' })).rejects.toThrow('Locked');
});
it('FE-HOOK-DASH-012: deleting drops the trip from both lists', async () => {
server.use(http.delete('/api/trips/:id', () => HttpResponse.json({ success: true })));
const { result } = await mountLoaded();
act(() => { result.current.setDeleteTrip(PARIS); });
await act(async () => { await result.current.confirmDelete(); });
act(() => result.current.setTripFilter('completed'));
expect(result.current.gridTrips).toHaveLength(0);
expect(result.current.deleteTrip).toBeNull();
expect(toastCalls).toContainEqual(['Trip deleted', 'success']);
});
it('FE-HOOK-DASH-013: confirming a delete without a target does nothing', async () => {
const { result } = await mountLoaded();
await act(async () => { await result.current.confirmDelete(); });
expect(toastCalls).toEqual([]);
});
it('FE-HOOK-DASH-014: a failing delete toasts and keeps the trip', async () => {
server.use(http.delete('/api/trips/:id', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
const { result } = await mountLoaded();
act(() => { result.current.setDeleteTrip(PARIS); });
await act(async () => { await result.current.confirmDelete(); });
expect(toastCalls).toContainEqual(['Failed to delete trip', 'error']);
act(() => result.current.setTripFilter('completed'));
expect(result.current.gridTrips).toHaveLength(1);
});
it('FE-HOOK-DASH-015: archiving moves the trip into the archive list', async () => {
server.use(http.put('/api/trips/:id', () => HttpResponse.json({ trip: { ...PARIS, is_archived: 1 } })));
const { result } = await mountLoaded();
await act(async () => { await result.current.handleArchive(101); });
act(() => result.current.setTripFilter('archive'));
expect(result.current.gridTrips.map(t => t.id)).toContain(101);
expect(toastCalls).toContainEqual(['Trip archived', 'success']);
});
it('FE-HOOK-DASH-016: a failing archive only toasts', async () => {
server.use(http.put('/api/trips/:id', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
const { result } = await mountLoaded();
await act(async () => { await result.current.handleArchive(101); });
expect(toastCalls).toContainEqual(['Failed to archive trip', 'error']);
});
it('FE-HOOK-DASH-017: restoring moves the trip back into the active list', async () => {
server.use(http.put('/api/trips/:id', () => HttpResponse.json({ trip: { ...ROME, is_archived: 0 } })));
const { result } = await mountLoaded();
await act(async () => { await result.current.handleUnarchive(103); });
act(() => result.current.setTripFilter('archive'));
expect(result.current.gridTrips).toHaveLength(0);
act(() => result.current.setTripFilter('completed'));
expect(result.current.gridTrips.map(t => t.id)).toContain(103);
expect(toastCalls).toContainEqual(['Trip restored', 'success']);
});
it('FE-HOOK-DASH-018: a failing restore only toasts', async () => {
server.use(http.put('/api/trips/:id', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
const { result } = await mountLoaded();
await act(async () => { await result.current.handleUnarchive(103); });
expect(toastCalls).toContainEqual(['Failed to restore trip', 'error']);
});
it('FE-HOOK-DASH-019: copying adds the duplicate and clears the dialog', async () => {
server.use(http.post('/api/trips/:id/copy', async ({ request }) => {
const body = await request.json() as { title: string };
return HttpResponse.json({ trip: { ...PARIS, id: 300, title: body.title } });
}));
const { result } = await mountLoaded();
act(() => { result.current.setCopyTrip(PARIS); });
await act(async () => { await result.current.confirmCopy(); });
act(() => result.current.setTripFilter('completed'));
expect(result.current.gridTrips.map(t => t.title)).toContain('Paris Adventure (copy)');
expect(result.current.copyTrip).toBeNull();
});
it('FE-HOOK-DASH-020: copying without a target does nothing', async () => {
const { result } = await mountLoaded();
await act(async () => { await result.current.confirmCopy(); });
expect(toastCalls).toEqual([]);
});
it('FE-HOOK-DASH-021: a failing copy only toasts', async () => {
server.use(http.post('/api/trips/:id/copy', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
const { result } = await mountLoaded();
act(() => { result.current.setCopyTrip(PARIS); });
await act(async () => { await result.current.confirmCopy(); });
expect(toastCalls).toContainEqual(['Failed to copy trip', 'error']);
});
it('FE-HOOK-DASH-022: the view mode toggle persists to localStorage', async () => {
const { result } = await mountLoaded();
expect(result.current.viewMode).toBe('grid');
act(() => { result.current.toggleViewMode(); });
expect(result.current.viewMode).toBe('list');
expect(localStorage.getItem('trek_dashboard_view')).toBe('list');
act(() => { result.current.toggleViewMode(); });
expect(localStorage.getItem('trek_dashboard_view')).toBe('grid');
});
it('FE-HOOK-DASH-023: the hero bundle follows the spotlight trip', async () => {
server.use(http.get('/api/trips/:id/bundle', () =>
HttpResponse.json({ members: [{ id: 1, username: 'maurice' }], places: [] })));
const { result } = await mountLoaded();
await waitFor(() => expect(result.current.heroBundle?.members).toHaveLength(1));
});
it('FE-HOOK-DASH-024: a failing bundle leaves the hero without extras', async () => {
server.use(http.get('/api/trips/:id/bundle', () => HttpResponse.json({ error: 'nope' }, { status: 500 })));
const { result } = await mountLoaded();
await waitFor(() => expect(result.current.heroBundle).toBeNull());
});
it('FE-HOOK-DASH-025: an account without trips has no spotlight at all', async () => {
tripsHandler([]);
const { result } = await mountLoaded();
expect(result.current.spotlight).toBeNull();
expect(result.current.heroBundle).toBeNull();
});
});
@@ -0,0 +1,100 @@
// FE-PAGE-FORGOT-001 to FE-PAGE-FORGOT-008
import { act, renderHook, waitFor } from '@testing-library/react';
import type { FormEvent } from 'react';
import { authApi } from '../../api/client';
import { useForgotPassword } from './useForgotPassword';
const navigate = vi.fn();
vi.mock('react-router-dom', () => ({ useNavigate: () => navigate }));
const submitEvent = () => ({ preventDefault: vi.fn() }) as unknown as FormEvent;
beforeEach(() => {
navigate.mockClear();
vi.spyOn(authApi, 'getAppConfig').mockResolvedValue({ available_channels: { email: true } } as never);
vi.spyOn(authApi, 'forgotPassword').mockResolvedValue({} as never);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('useForgotPassword', () => {
it('FE-PAGE-FORGOT-001: starts with an empty, unsubmitted form', async () => {
const { result } = renderHook(() => useForgotPassword());
expect(result.current.email).toBe('');
expect(result.current.submitted).toBe(false);
expect(result.current.isLoading).toBe(false);
await waitFor(() => expect(result.current.smtpConfigured).toBe(true));
});
it('FE-PAGE-FORGOT-002: reports SMTP as unconfigured when the server has no email channel', async () => {
vi.mocked(authApi.getAppConfig).mockResolvedValue({ available_channels: { email: false } } as never);
const { result } = renderHook(() => useForgotPassword());
await waitFor(() => expect(result.current.smtpConfigured).toBe(false));
});
it('FE-PAGE-FORGOT-003: treats a missing config payload as unconfigured', async () => {
vi.mocked(authApi.getAppConfig).mockResolvedValue(null as never);
const { result } = renderHook(() => useForgotPassword());
await waitFor(() => expect(result.current.smtpConfigured).toBe(false));
});
it('FE-PAGE-FORGOT-004: leaves the hint hidden when the probe fails', async () => {
vi.mocked(authApi.getAppConfig).mockRejectedValue(new Error('offline'));
const { result } = renderHook(() => useForgotPassword());
await waitFor(() => expect(authApi.getAppConfig).toHaveBeenCalled());
expect(result.current.smtpConfigured).toBeNull();
});
it('FE-PAGE-FORGOT-005: submits the trimmed address and switches to the sent state', async () => {
const { result } = renderHook(() => useForgotPassword());
act(() => result.current.setEmail(' maurice@trek.app '));
const event = submitEvent();
await act(() => result.current.handleSubmit(event));
expect(event.preventDefault).toHaveBeenCalled();
expect(authApi.forgotPassword).toHaveBeenCalledWith({ email: 'maurice@trek.app' });
expect(result.current.submitted).toBe(true);
expect(result.current.isLoading).toBe(false);
});
it('FE-PAGE-FORGOT-006: shows the same success state when the server rejects — no account enumeration', async () => {
vi.mocked(authApi.forgotPassword).mockRejectedValue(new Error('no such user'));
const { result } = renderHook(() => useForgotPassword());
act(() => result.current.setEmail('ghost@trek.app'));
await act(() => result.current.handleSubmit(submitEvent()));
expect(result.current.submitted).toBe(true);
});
it('FE-PAGE-FORGOT-007: ignores a second submit while the first is in flight', async () => {
let release: (() => void) | undefined;
vi.mocked(authApi.forgotPassword).mockReturnValue(new Promise(res => { release = () => res({} as never); }) as never);
const { result } = renderHook(() => useForgotPassword());
act(() => result.current.setEmail('maurice@trek.app'));
let first: Promise<void>;
act(() => { first = result.current.handleSubmit(submitEvent()) as Promise<void>; });
expect(result.current.isLoading).toBe(true);
await act(() => result.current.handleSubmit(submitEvent()));
expect(authApi.forgotPassword).toHaveBeenCalledTimes(1);
await act(async () => { release!(); await first; });
expect(result.current.submitted).toBe(true);
});
it('FE-PAGE-FORGOT-008: hands the router navigate through to the page', async () => {
const { result } = renderHook(() => useForgotPassword());
expect(result.current.navigate).toBe(navigate);
await waitFor(() => expect(result.current.smtpConfigured).toBe(true));
});
});
+150
View File
@@ -0,0 +1,150 @@
// FE-PAGE-HELP-001 to FE-PAGE-HELP-012
import { act, renderHook, waitFor } from '@testing-library/react';
import { helpApi, type HelpNavSection, type HelpPageData } from '../../api/client';
import { useHelp } from './useHelp';
let routeParams: { slug?: string } = {};
vi.mock('react-router-dom', () => ({ useParams: () => routeParams }));
const SECTIONS: HelpNavSection[] = [
{ title: 'Getting started', pages: [{ slug: 'Home', title: 'Welcome' }, { slug: 'Install', title: 'Installation' }] },
{ title: 'Guides', pages: [{ slug: 'Trips', title: 'Planning a trip' }, { slug: 'Budget', title: 'Splitting costs' }] },
] as HelpNavSection[];
const PAGE = { slug: 'Home', title: 'Welcome', body: '# Welcome' } as unknown as HelpPageData;
beforeEach(() => {
routeParams = {};
// jsdom has no scrollTo and logs a "Not implemented" error for every call.
vi.stubGlobal('scrollTo', vi.fn());
vi.spyOn(helpApi, 'index').mockResolvedValue({ sections: SECTIONS } as never);
vi.spyOn(helpApi, 'page').mockResolvedValue(PAGE as never);
});
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
describe('useHelp', () => {
it('FE-PAGE-HELP-001: loads the navigation and the landing page', async () => {
const { result } = renderHook(() => useHelp());
expect(result.current.loading).toBe(true);
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.filtered).toEqual(SECTIONS);
expect(result.current.page).toEqual(PAGE);
expect(result.current.pageError).toBe(false);
});
it('FE-PAGE-HELP-002: defaults to the first page in the index when the route has no slug', async () => {
renderHook(() => useHelp());
await waitFor(() => expect(helpApi.page).toHaveBeenLastCalledWith('Home'));
});
it('FE-PAGE-HELP-003: falls back to the Home slug while the index is still loading', () => {
renderHook(() => useHelp());
expect(helpApi.page).toHaveBeenCalledWith('Home');
});
it('FE-PAGE-HELP-004: honours the slug from the route', async () => {
routeParams = { slug: 'Budget' };
const { result } = renderHook(() => useHelp());
await waitFor(() => expect(result.current.activeSlug).toBe('Budget'));
expect(helpApi.page).toHaveBeenCalledWith('Budget');
});
it('FE-PAGE-HELP-005: keeps an empty navigation when the index request fails', async () => {
vi.mocked(helpApi.index).mockRejectedValue(new Error('offline'));
const { result } = renderHook(() => useHelp());
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.filtered).toEqual([]);
});
it('FE-PAGE-HELP-006: flags a page that could not be fetched', async () => {
vi.mocked(helpApi.page).mockRejectedValue(new Error('404'));
const { result } = renderHook(() => useHelp());
await waitFor(() => expect(result.current.pageError).toBe(true));
expect(result.current.loading).toBe(false);
expect(result.current.page).toBeNull();
});
it('FE-PAGE-HELP-007: filters the navigation by page title, case-insensitively', async () => {
const { result } = renderHook(() => useHelp());
await waitFor(() => expect(result.current.filtered).toHaveLength(2));
act(() => result.current.setQuery(' PLAN '));
expect(result.current.filtered).toEqual([
{ title: 'Guides', pages: [{ slug: 'Trips', title: 'Planning a trip' }] },
]);
});
it('FE-PAGE-HELP-008: drops sections that no longer have a matching page', async () => {
const { result } = renderHook(() => useHelp());
await waitFor(() => expect(result.current.filtered).toHaveLength(2));
act(() => result.current.setQuery('zzz'));
expect(result.current.filtered).toEqual([]);
});
it('FE-PAGE-HELP-009: an empty query restores the full navigation', async () => {
const { result } = renderHook(() => useHelp());
await waitFor(() => expect(result.current.filtered).toHaveLength(2));
act(() => result.current.setQuery('install'));
expect(result.current.filtered).toHaveLength(1);
act(() => result.current.setQuery(' '));
expect(result.current.filtered).toEqual(SECTIONS);
});
it('FE-PAGE-HELP-010: scrolls back to the top and closes the mobile nav on navigation', async () => {
const scrollTo = vi.mocked(window.scrollTo);
const { result, rerender } = renderHook(() => useHelp());
await waitFor(() => expect(result.current.loading).toBe(false));
act(() => result.current.setNavOpen(true));
expect(result.current.navOpen).toBe(true);
routeParams = { slug: 'Trips' };
rerender();
await waitFor(() => expect(result.current.navOpen).toBe(false));
expect(scrollTo).toHaveBeenCalledWith({ top: 0 });
});
it('FE-PAGE-HELP-011: scrolls the content pane when the ref is attached', async () => {
const { result, rerender } = renderHook(() => useHelp());
await waitFor(() => expect(result.current.loading).toBe(false));
const scrollTo = vi.fn();
(result.current.contentRef as { current: unknown }).current = { scrollTo };
routeParams = { slug: 'Install' };
rerender();
await waitFor(() => expect(scrollTo).toHaveBeenCalledWith({ top: 0 }));
});
it('FE-PAGE-HELP-012: a page arriving after a slug change does not overwrite the newer one', async () => {
let resolveFirst: ((p: HelpPageData) => void) | undefined;
vi.mocked(helpApi.page).mockImplementationOnce(
() => new Promise(res => { resolveFirst = res as (p: HelpPageData) => void; }) as never,
);
const { result, rerender } = renderHook(() => useHelp());
routeParams = { slug: 'Trips' };
rerender();
await waitFor(() => expect(result.current.page).toEqual(PAGE));
const stale = { slug: 'Home', title: 'Stale', body: '' } as unknown as HelpPageData;
await act(async () => { resolveFirst!(stale); });
expect(result.current.page).toEqual(PAGE);
});
});
+116
View File
@@ -0,0 +1,116 @@
// FE-PAGE-JOIN-001 to FE-PAGE-JOIN-008
import { act, renderHook, waitFor } from '@testing-library/react';
import { tripInviteApi } from '../../api/client';
import { useJoinTrip } from './useJoinTrip';
const navigate = vi.fn();
let params: { token?: string } = { token: 'inv-1' };
vi.mock('react-router-dom', () => ({
useNavigate: () => navigate,
useParams: () => params,
}));
beforeEach(() => {
navigate.mockClear();
params = { token: 'inv-1' };
vi.spyOn(tripInviteApi, 'preview').mockResolvedValue({ title: 'Japan 2026' } as never);
vi.spyOn(tripInviteApi, 'accept').mockResolvedValue({ trip_id: 42 } as never);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('useJoinTrip', () => {
it('FE-PAGE-JOIN-001: resolves the invite to a trip title', async () => {
const { result } = renderHook(() => useJoinTrip());
expect(result.current.state).toBe('loading');
await waitFor(() => expect(result.current.state).toBe('ready'));
expect(result.current.title).toBe('Japan 2026');
expect(tripInviteApi.preview).toHaveBeenCalledWith('inv-1');
});
it('FE-PAGE-JOIN-002: goes straight to invalid without a token in the URL', async () => {
params = {};
const { result } = renderHook(() => useJoinTrip());
expect(result.current.state).toBe('invalid');
expect(tripInviteApi.preview).not.toHaveBeenCalled();
});
it('FE-PAGE-JOIN-003: marks a rejected invite invalid', async () => {
vi.mocked(tripInviteApi.preview).mockRejectedValue(new Error('expired'));
const { result } = renderHook(() => useJoinTrip());
await waitFor(() => expect(result.current.state).toBe('invalid'));
expect(result.current.title).toBe('');
});
it('FE-PAGE-JOIN-004: accepting opens the trip and replaces the invite URL', async () => {
const { result } = renderHook(() => useJoinTrip());
await waitFor(() => expect(result.current.state).toBe('ready'));
await act(() => { result.current.accept(); return Promise.resolve(); });
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/trips/42', { replace: true }));
expect(tripInviteApi.accept).toHaveBeenCalledWith('inv-1');
});
it('FE-PAGE-JOIN-005: shows the joining state while the invite is redeemed', async () => {
let release: (() => void) | undefined;
vi.mocked(tripInviteApi.accept).mockReturnValue(
new Promise(res => { release = () => res({ trip_id: 7 } as never); }) as never,
);
const { result } = renderHook(() => useJoinTrip());
await waitFor(() => expect(result.current.state).toBe('ready'));
act(() => result.current.accept());
expect(result.current.state).toBe('joining');
await act(async () => { release!(); });
await waitFor(() => expect(navigate).toHaveBeenCalledWith('/trips/7', { replace: true }));
});
it('FE-PAGE-JOIN-006: falls back to invalid when redeeming fails', async () => {
vi.mocked(tripInviteApi.accept).mockRejectedValue(new Error('already a member'));
const { result } = renderHook(() => useJoinTrip());
await waitFor(() => expect(result.current.state).toBe('ready'));
act(() => result.current.accept());
await waitFor(() => expect(result.current.state).toBe('invalid'));
expect(navigate).not.toHaveBeenCalled();
});
it('FE-PAGE-JOIN-007: accept is a no-op without a token', () => {
params = {};
const { result } = renderHook(() => useJoinTrip());
act(() => result.current.accept());
expect(tripInviteApi.accept).not.toHaveBeenCalled();
expect(result.current.state).toBe('invalid');
});
it('FE-PAGE-JOIN-008: the dashboard escape hatch replaces the invite URL too', async () => {
const { result } = renderHook(() => useJoinTrip());
await waitFor(() => expect(result.current.state).toBe('ready'));
act(() => result.current.goToDashboard());
expect(navigate).toHaveBeenCalledWith('/dashboard', { replace: true });
});
it('FE-PAGE-JOIN-009: a preview landing after unmount does not update state', async () => {
let release: ((v: { title: string }) => void) | undefined;
vi.mocked(tripInviteApi.preview).mockReturnValue(
new Promise(res => { release = res as (v: { title: string }) => void; }) as never,
);
const { result, unmount } = renderHook(() => useJoinTrip());
unmount();
await act(async () => { release!({ title: 'Too late' }); });
expect(result.current.state).toBe('loading');
});
});
@@ -0,0 +1,340 @@
// FE-JRN-DETHOOK-001 to FE-JRN-DETHOOK-022
import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest';
import { useLocation } from 'react-router-dom';
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render';
import { addListener, removeListener } from '../../api/websocket';
import { useJourneyStore } from '../../store/journeyStore';
import type { JourneyDetail, JourneyEntry } from '../../store/journeyStore';
import { useJourneyDetail } from './useJourneyDetail';
let routeParams: { id?: string } = { id: '7' };
const mockNavigate = vi.fn();
let mockIsMobile = false;
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual<typeof import('react-router-dom')>('react-router-dom');
return { ...actual, useParams: () => routeParams, useNavigate: () => mockNavigate };
});
vi.mock('../../hooks/useIsMobile', () => ({ useIsMobile: () => mockIsMobile }));
type AddToast = NonNullable<typeof window.__addToast>;
let addToast: Mock<AddToast>;
const journeyStoreInitial = useJourneyStore.getState();
// ── Fixtures ─────────────────────────────────────────────────────────────────
function buildEntry(over: Partial<JourneyEntry> = {}): JourneyEntry {
return {
id: 1, journey_id: 7, author_id: 1, type: 'entry', title: 'Arrival', story: null,
entry_date: '2026-05-01', entry_time: null, location_name: 'Tokyo',
location_lat: 35.6, location_lng: 139.7, mood: 'good', weather: null,
tags: [], pros_cons: null, visibility: 'private', sort_order: 0, photos: [],
created_at: 0, updated_at: 0,
...over,
};
}
function buildDetail(over: Partial<JourneyDetail> = {}): JourneyDetail {
return {
id: 7, user_id: 1, title: 'Japan 2026', subtitle: null, cover_gradient: null,
cover_image: null, status: 'active', created_at: 0, updated_at: 0,
entries: [buildEntry(), buildEntry({ id: 2, title: 'Kyoto', entry_date: '2026-05-02' })],
gallery: [], trips: [], contributors: [],
stats: { entries: 2, photos: 0, places: 0 },
...over,
};
}
function serveJourney(detail: JourneyDetail | Record<string, unknown>): void {
server.use(http.get('/api/journeys/7', () => HttpResponse.json(detail)));
}
// ── Harness ──────────────────────────────────────────────────────────────────
type HookState = ReturnType<typeof useJourneyDetail>;
let latest: HookState;
function Harness({ renderEntries = true }: { renderEntries?: boolean }) {
const state = useJourneyDetail();
latest = state;
const location = useLocation();
return (
<div>
<span data-testid="search">{location.search}</span>
<div ref={state.feedRef} data-testid="feed">
{renderEntries && (state.current?.entries ?? []).map(e => (
<div key={e.id} data-entry-id={String(e.id)} data-testid={`entry-${e.id}`}>{e.title}</div>
))}
{renderEntries && <div data-entry-id="" data-testid="entry-blank" />}
</div>
</div>
);
}
function setup(options: { search?: string; renderEntries?: boolean } = {}) {
return render(<Harness renderEntries={options.renderEntries} />, {
initialEntries: [`/journey/7${options.search ?? ''}`],
});
}
/** Feed the layout numbers commitWinner reads out of the DOM. */
function stubRects(tops: Record<string, number>): void {
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) {
const key = this.getAttribute('data-entry-id') ?? 'feed';
const top = tops[key] ?? 0;
return { top, bottom: top, left: 0, right: 0, width: 0, height: 0, x: 0, y: top, toJSON: () => ({}) } as DOMRect;
});
}
beforeEach(() => {
routeParams = { id: '7' };
mockIsMobile = false;
vi.clearAllMocks();
addToast = vi.fn<AddToast>(() => 0);
window.__addToast = addToast;
useJourneyStore.setState(journeyStoreInitial, true);
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => { cb(0); return 1; });
vi.stubGlobal('cancelAnimationFrame', vi.fn());
serveJourney(buildDetail());
});
afterEach(() => {
delete window.__addToast;
vi.restoreAllMocks();
vi.unstubAllGlobals();
useJourneyStore.setState(journeyStoreInitial, true);
});
// ── Tests ────────────────────────────────────────────────────────────────────
describe('useJourneyDetail', () => {
it('FE-JRN-DETHOOK-001: loads the journey named in the route', async () => {
setup();
await waitFor(() => expect(latest.current?.title).toBe('Japan 2026'));
expect(latest.loading).toBe(false);
expect(latest.id).toBe('7');
});
it('FE-JRN-DETHOOK-002: a missing route id skips the load', async () => {
routeParams = {};
setup();
await waitFor(() => expect(latest.current).toBeNull());
expect(addListener).not.toHaveBeenCalled();
});
it('FE-JRN-DETHOOK-003: ?create=entry opens a draft entry and drops the parameter', async () => {
setup({ search: '?create=entry' });
await waitFor(() => expect(latest.editingEntry).not.toBeNull());
expect(latest.editingEntry).toMatchObject({ id: 0, journey_id: 7, type: 'entry', visibility: 'private' });
expect(screen.getByTestId('search')).toHaveTextContent('');
});
it('FE-JRN-DETHOOK-004: a viewer never gets the draft editor', async () => {
serveJourney({ ...buildDetail(), my_role: 'viewer' });
setup({ search: '?create=entry' });
await waitFor(() => expect(latest.current).not.toBeNull());
expect(latest.canEditEntries).toBe(false);
expect(latest.canEditJourney).toBe(false);
expect(latest.editingEntry).toBeNull();
});
it('FE-JRN-DETHOOK-005: an editor may edit entries but not the journey itself', async () => {
serveJourney({ ...buildDetail(), my_role: 'editor' });
setup();
await waitFor(() => expect(latest.myRole).toBe('editor'));
expect(latest.canEditEntries).toBe(true);
expect(latest.canEditJourney).toBe(false);
});
it('FE-JRN-DETHOOK-006: the stored hide_skeletons preference seeds the toggle', async () => {
serveJourney({ ...buildDetail(), hide_skeletons: true });
setup();
await waitFor(() => expect(latest.hideSkeletons).toBe(true));
});
it('FE-JRN-DETHOOK-007: a 404 reports it and returns to the journey list', async () => {
server.use(http.get('/api/journeys/7', () => HttpResponse.json({ error: 'gone' }, { status: 404 })));
setup();
await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith('/journey'));
expect(addToast).toHaveBeenCalledWith('Journey not found', 'error', undefined);
});
it('FE-JRN-DETHOOK-008: a websocket journey event for this journey triggers a reload', async () => {
setup();
await waitFor(() => expect(latest.current).not.toBeNull());
const handler = vi.mocked(addListener).mock.calls[0][0] as (e: Record<string, unknown>) => void;
serveJourney(buildDetail({ title: 'Japan renamed' }));
handler({ type: 'journey:entry_created', journeyId: 7 });
await waitFor(() => expect(latest.current?.title).toBe('Japan renamed'));
});
it('FE-JRN-DETHOOK-009: events of another type or another journey are ignored', async () => {
setup();
await waitFor(() => expect(latest.current).not.toBeNull());
const handler = vi.mocked(addListener).mock.calls[0][0] as (e: Record<string, unknown>) => void;
serveJourney(buildDetail({ title: 'Should not appear' }));
handler({ type: 'trip:updated', journeyId: 7 });
handler({ type: 'journey:entry_created', journeyId: 99 });
handler({ journeyId: 7 });
await new Promise(r => setTimeout(r, 20));
expect(latest.current?.title).toBe('Japan 2026');
});
it('FE-JRN-DETHOOK-010: the websocket listener is detached on unmount', async () => {
const { unmount } = setup();
await waitFor(() => expect(addListener).toHaveBeenCalled());
unmount();
expect(removeListener).toHaveBeenCalledWith(vi.mocked(addListener).mock.calls[0][0]);
});
it('FE-JRN-DETHOOK-011: scroll sync selects the last entry above the reference line', async () => {
setup();
await waitFor(() => expect(latest.current).not.toBeNull());
stubRects({ '1': -50, '2': -10, feed: 0 });
fireEvent.scroll(screen.getByTestId('feed'));
await waitFor(() => expect(latest.activeEntryId).toBe('2'));
});
it('FE-JRN-DETHOOK-012: with every entry below the line the closest one wins', async () => {
setup();
await waitFor(() => expect(latest.current).not.toBeNull());
stubRects({ '1': 300, '2': 120, feed: 0 });
fireEvent.scroll(screen.getByTestId('feed'));
await waitFor(() => expect(latest.activeEntryId).toBe('2'));
});
it('FE-JRN-DETHOOK-013: a feed without entry nodes leaves the selection empty', async () => {
setup({ renderEntries: false });
await waitFor(() => expect(latest.current).not.toBeNull());
fireEvent.scroll(screen.getByTestId('feed'));
await new Promise(r => setTimeout(r, 20));
expect(latest.activeEntryId).toBeNull();
});
it('FE-JRN-DETHOOK-014: clicking a marker pins the entry and suppresses the scroll sync', async () => {
vi.useFakeTimers();
try {
setup();
await vi.waitFor(() => expect(latest.current).not.toBeNull());
const el = screen.getByTestId('entry-2');
const scrollIntoView = vi.spyOn(el, 'scrollIntoView');
latest.handleMarkerClick('2');
await vi.waitFor(() => expect(latest.activeEntryId).toBe('2'));
expect(scrollIntoView).toHaveBeenCalledWith({ behavior: 'smooth', block: 'center' });
// While suppressed a scroll must not move the selection elsewhere.
stubRects({ '1': -50, '2': 400, feed: 0 });
fireEvent.scroll(screen.getByTestId('feed'));
expect(latest.activeEntryId).toBe('2');
vi.advanceTimersByTime(800);
fireEvent.scroll(screen.getByTestId('feed'));
await vi.waitFor(() => expect(latest.activeEntryId).toBe('1'));
} finally {
vi.useRealTimers();
}
});
it('FE-JRN-DETHOOK-015: a pending animation frame is cancelled when the feed unmounts', async () => {
const cancel = vi.fn();
vi.stubGlobal('requestAnimationFrame', () => 42);
vi.stubGlobal('cancelAnimationFrame', cancel);
const { unmount } = setup();
// The sync attaches 300ms after the entries land and primes the selection.
await waitFor(() => expect(latest.activeEntryId).not.toBeNull());
fireEvent.scroll(screen.getByTestId('feed'));
unmount();
expect(cancel).toHaveBeenCalledWith(42);
});
it('FE-JRN-DETHOOK-016: handleLocationClick records the clicked location', async () => {
setup();
await waitFor(() => expect(latest.current).not.toBeNull());
latest.handleLocationClick('loc-3');
await waitFor(() => expect(latest.activeLocationId).toBe('loc-3'));
});
it('FE-JRN-DETHOOK-017: only located, non-skeleton entries reach the map', async () => {
serveJourney(buildDetail({
entries: [
buildEntry({ id: 1 }),
buildEntry({ id: 2, title: 'Gallery' }),
buildEntry({ id: 3, title: '[Trip Photos]' }),
buildEntry({ id: 4, type: 'skeleton', title: 'Suggested' }),
buildEntry({ id: 5, title: 'No GPS', location_lat: null, location_lng: null }),
buildEntry({ id: 6, title: 'Later', entry_date: '2026-05-02' }),
],
}));
setup();
await waitFor(() => expect(latest.mapEntries).toHaveLength(2));
expect(latest.mapEntries.map(e => e.id)).toEqual([1, 6]);
expect(latest.sidebarMapItems.map(m => m.id)).toEqual(['1', '6']);
expect(latest.sidebarMapItems[0].dayLabel).toBe(1);
expect(latest.sidebarMapItems[0].dayColor).not.toBe(latest.sidebarMapItems[1].dayColor);
});
it('FE-JRN-DETHOOK-018: two entries on one day get consecutive day labels and one colour', async () => {
serveJourney(buildDetail({
entries: [buildEntry({ id: 1 }), buildEntry({ id: 2, title: 'Second stop' })],
}));
setup();
await waitFor(() => expect(latest.sidebarMapItems).toHaveLength(2));
expect(latest.sidebarMapItems.map(m => m.dayLabel)).toEqual([1, 2]);
expect(latest.sidebarMapItems[0].dayColor).toBe(latest.sidebarMapItems[1].dayColor);
});
it('FE-JRN-DETHOOK-019: tripDates expands linked trips and skips half-dated ones', async () => {
serveJourney(buildDetail({
trips: [
{ trip_id: 1, added_at: 0, title: 'Tokyo', start_date: '2026-05-01', end_date: '2026-05-03', cover_image: null, currency: 'EUR', place_count: 0 },
{ trip_id: 2, added_at: 0, title: 'Open ended', start_date: '2026-06-01', end_date: null, cover_image: null, currency: 'EUR', place_count: 0 },
],
}));
setup();
// Three consecutive days for the closed trip, nothing for the open-ended one.
// The keys themselves are UTC-shifted (see report), so assert the shape.
await waitFor(() => expect(latest.tripDates.size).toBe(3));
const dates = [...latest.tripDates].sort();
expect(new Date(dates[2]).getTime() - new Date(dates[0]).getTime()).toBe(2 * 86400000);
expect(dates.some(d => d.startsWith('2026-06'))).toBe(false);
});
it('FE-JRN-DETHOOK-020: the desktop two-pane layout locks body scroll and restores it', async () => {
document.body.style.overflow = 'auto';
const { unmount } = setup();
await waitFor(() => expect(document.body.style.overflow).toBe('hidden'));
unmount();
expect(document.body.style.overflow).toBe('auto');
});
it('FE-JRN-DETHOOK-021: on mobile the body keeps scrolling', async () => {
mockIsMobile = true;
document.body.style.overflow = 'auto';
setup();
await waitFor(() => expect(latest.current).not.toBeNull());
expect(latest.isMobile).toBe(true);
expect(document.body.style.overflow).toBe('auto');
});
it('FE-JRN-DETHOOK-022: switching the view re-measures the sidebar map', async () => {
setup();
await waitFor(() => expect(latest.current).not.toBeNull());
const invalidateSize = vi.fn();
latest.mapRef.current = { invalidateSize, highlightMarker: vi.fn(), focusMarker: vi.fn() } as never;
fireEvent.click(document.body);
latest.setView('gallery');
await waitFor(() => expect(invalidateSize).toHaveBeenCalled());
expect(latest.view).toBe('gallery');
});
});
+317
View File
@@ -0,0 +1,317 @@
// FE-LOGIN-WORLD-001 to FE-LOGIN-WORLD-014
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { render } from '../../../tests/helpers/render';
import LoginWorld from './LoginWorld';
// jsdom has no 2D context, so both the visible canvas and the offscreen dot layer
// get a recording stand-in. Contexts land in `contexts` in creation order:
// [0] is the visible canvas, [1] the first baked map layer.
function makeCtx() {
const strokeStyles: string[] = [];
const ctx = {
setTransform: vi.fn(),
scale: vi.fn(),
clearRect: vi.fn(),
drawImage: vi.fn(),
beginPath: vi.fn(),
arc: vi.fn(),
fill: vi.fn(),
moveTo: vi.fn(),
lineTo: vi.fn(),
stroke: vi.fn(),
createRadialGradient: vi.fn(() => ({ addColorStop: vi.fn() })),
lineWidth: 0,
fillStyle: '' as unknown,
strokeStyles,
};
Object.defineProperty(ctx, 'strokeStyle', {
get: () => strokeStyles[strokeStyles.length - 1] ?? '',
set: (value: string) => {
strokeStyles.push(value);
},
});
return ctx;
}
type FakeCtx = ReturnType<typeof makeCtx>;
const origGetContext = HTMLCanvasElement.prototype.getContext;
const origRect = HTMLCanvasElement.prototype.getBoundingClientRect;
const origRaf = window.requestAnimationFrame;
const origCancel = window.cancelAnimationFrame;
const origRandom = Math.random;
const origDpr = window.devicePixelRatio;
let contexts: FakeCtx[] = [];
let queue: FrameRequestCallback[] = [];
let now = 0;
let cancelSpy: ReturnType<typeof vi.fn>;
let rectWidth = 800;
let rectHeight = 600;
/** How many getContext calls hand back a context before returning null. */
let contextBudget = Infinity;
function installContexts() {
contexts = [];
HTMLCanvasElement.prototype.getContext = vi.fn(() => {
if (contexts.length >= contextBudget) return null;
const ctx = makeCtx();
contexts.push(ctx);
return ctx;
}) as unknown as HTMLCanvasElement['getContext'];
}
/** Deterministic stand-in for Math.random so arc endpoints and timings repeat. */
function seedRandom(seed = 1) {
let state = seed;
Math.random = () => {
state = (state * 9301 + 49297) % 233280;
return state / 233280;
};
}
function runFrames(count: number, dt = 48): number {
for (let i = 0; i < count; i++) {
const cb = queue.shift();
if (!cb) return i;
now += dt;
cb(now);
}
return count;
}
function alphasOf(ctx: FakeCtx): number[] {
return ctx.strokeStyles.map((s) => Number(/,\s*([\d.]+)\)$/.exec(s)?.[1] ?? NaN));
}
beforeEach(() => {
rectWidth = 800;
rectHeight = 600;
contextBudget = Infinity;
queue = [];
now = 0;
seedRandom();
installContexts();
HTMLCanvasElement.prototype.getBoundingClientRect = () =>
({
width: rectWidth,
height: rectHeight,
top: 0,
left: 0,
right: rectWidth,
bottom: rectHeight,
x: 0,
y: 0,
toJSON: () => ({}),
}) as DOMRect;
window.requestAnimationFrame = ((cb: FrameRequestCallback) => {
queue.push(cb);
return queue.length;
}) as typeof window.requestAnimationFrame;
cancelSpy = vi.fn();
window.cancelAnimationFrame = cancelSpy as typeof window.cancelAnimationFrame;
});
afterEach(() => {
HTMLCanvasElement.prototype.getContext = origGetContext;
HTMLCanvasElement.prototype.getBoundingClientRect = origRect;
window.requestAnimationFrame = origRaf;
window.cancelAnimationFrame = origCancel;
Math.random = origRandom;
Object.defineProperty(window, 'devicePixelRatio', { configurable: true, writable: true, value: origDpr });
vi.unstubAllGlobals();
});
describe('LoginWorld', () => {
it('FE-LOGIN-WORLD-001: renders a decorative canvas that never takes pointer events', () => {
const { container } = render(<LoginWorld />);
const canvas = container.querySelector('canvas')!;
expect(canvas).toHaveAttribute('aria-hidden');
expect(canvas.style.pointerEvents).toBe('none');
expect(canvas.style.position).toBe('absolute');
expect(canvas.className).toBe('');
});
it('FE-LOGIN-WORLD-002: marks the takeoff variant so the page can animate it in', () => {
const { container } = render(<LoginWorld variant="takeoff" />);
expect(container.querySelector('canvas')).toHaveClass('login-world-takeoff');
});
it('FE-LOGIN-WORLD-003: bakes the coastlines into an offscreen layer and blits it per frame', () => {
render(<LoginWorld />);
const [visible, layer] = contexts;
// The layer is drawn once at mount…
expect(layer.arc.mock.calls.length).toBeGreaterThan(500);
expect(visible.arc.mock.calls.length).toBe(0);
const layerDotsAtMount = layer.arc.mock.calls.length;
runFrames(5);
// …and only blitted afterwards, never redrawn.
expect(layer.arc.mock.calls.length).toBe(layerDotsAtMount);
expect(visible.drawImage).toHaveBeenCalledTimes(5);
expect(visible.drawImage).toHaveBeenLastCalledWith(expect.anything(), 0, 0, 800, 600);
expect(visible.clearRect).toHaveBeenLastCalledWith(0, 0, 800, 600);
});
it('FE-LOGIN-WORLD-004: culls dots that fall outside the panel', () => {
render(<LoginWorld />);
const drawn = contexts[1].arc.mock.calls.length;
// The map is scaled to cover the panel, so its sides run off it.
expect(drawn).toBeGreaterThan(0);
expect(drawn).toBeLessThan(7131);
});
it('FE-LOGIN-WORLD-005: caps the backing store at 2x device pixels', () => {
Object.defineProperty(window, 'devicePixelRatio', { configurable: true, writable: true, value: 3 });
const { container } = render(<LoginWorld />);
const canvas = container.querySelector('canvas')!;
expect(canvas.width).toBe(1600);
expect(canvas.height).toBe(1200);
expect(contexts[0].setTransform).toHaveBeenCalledWith(2, 0, 0, 2, 0, 0);
expect(contexts[1].scale).toHaveBeenCalledWith(2, 2);
});
it('FE-LOGIN-WORLD-006: falls back to 1x when the browser reports no pixel ratio', () => {
Object.defineProperty(window, 'devicePixelRatio', { configurable: true, writable: true, value: 0 });
const { container } = render(<LoginWorld />);
expect(container.querySelector('canvas')!.width).toBe(800);
expect(contexts[0].setTransform).toHaveBeenCalledWith(1, 0, 0, 1, 0, 0);
});
it('FE-LOGIN-WORLD-007: opens with routes already in flight and keeps spawning them', () => {
render(<LoginWorld />);
const visible = contexts[0];
runFrames(1);
// Three routes are seeded before the first frame, plus one from the spawn timer.
expect(visible.stroke.mock.calls.length).toBeGreaterThanOrEqual(3);
runFrames(200);
const before = visible.stroke.mock.calls.length;
runFrames(1);
const drawnThisFrame = visible.stroke.mock.calls.length - before;
expect(drawnThisFrame).toBeGreaterThan(0);
expect(drawnThisFrame).toBeLessThanOrEqual(7);
});
it('FE-LOGIN-WORLD-008: retires ambient routes by fading them out', () => {
render(<LoginWorld />);
runFrames(300);
const alphas = alphasOf(contexts[0]);
expect(alphas.length).toBeGreaterThan(0);
// Fresh routes draw at 0.5; a retiring one is dimmer.
expect(Math.max(...alphas)).toBeCloseTo(0.5, 5);
expect(Math.min(...alphas)).toBeLessThan(0.5);
});
it('FE-LOGIN-WORLD-009: fires the whole network on takeoff and never lets it fade', () => {
render(<LoginWorld variant="takeoff" />);
const visible = contexts[0];
// The cascade is staggered, so the opening frame is still empty.
runFrames(1);
expect(visible.stroke).not.toHaveBeenCalled();
runFrames(120);
const before = visible.stroke.mock.calls.length;
runFrames(1);
expect(visible.stroke.mock.calls.length - before).toBe(11);
expect(alphasOf(visible).every((a) => a === 0.5)).toBe(true);
});
it('FE-LOGIN-WORLD-010: draws a real route when the two random endpoints collide', () => {
// Every random draw is 0, so `from` and `to` both land on the first city and
// the collision fix-up has to move `to` along.
Math.random = () => 0;
render(<LoginWorld />);
runFrames(400);
const visible = contexts[0];
const start = visible.moveTo.mock.calls[0] as [number, number];
const end = visible.lineTo.mock.calls[visible.lineTo.mock.calls.length - 1] as [number, number];
expect(Math.hypot(end[0] - start[0], end[1] - start[1])).toBeGreaterThan(10);
// Arrival lights the destination city.
expect(visible.createRadialGradient.mock.calls.length).toBeGreaterThan(visible.stroke.mock.calls.length);
});
it('FE-LOGIN-WORLD-011: holds a still frame when the user asked for reduced motion', () => {
vi.stubGlobal(
'matchMedia',
vi.fn(() => ({ matches: true })),
);
render(<LoginWorld />);
expect(queue).toHaveLength(0);
expect(contexts[0].drawImage).toHaveBeenCalledTimes(1);
expect(contexts[0].stroke).not.toHaveBeenCalled();
});
it('FE-LOGIN-WORLD-015: leaves the still frame blank when the layer could not be baked', () => {
contextBudget = 1;
vi.stubGlobal(
'matchMedia',
vi.fn(() => ({ matches: true })),
);
render(<LoginWorld />);
expect(queue).toHaveLength(0);
expect(contexts[0].clearRect).toHaveBeenCalledTimes(1);
expect(contexts[0].drawImage).not.toHaveBeenCalled();
});
it('FE-LOGIN-WORLD-016: animates normally when the browser exposes no matchMedia', () => {
vi.stubGlobal('matchMedia', undefined);
render(<LoginWorld />);
expect(queue).toHaveLength(1);
runFrames(5);
expect(contexts[0].stroke.mock.calls.length).toBeGreaterThan(0);
});
it('FE-LOGIN-WORLD-012: rebakes the map on resize and stops listening once unmounted', () => {
const { unmount } = render(<LoginWorld />);
expect(contexts).toHaveLength(2);
rectWidth = 500;
rectHeight = 400;
window.dispatchEvent(new Event('resize'));
expect(contexts).toHaveLength(3);
expect(contexts[0].setTransform).toHaveBeenCalledTimes(2);
unmount();
expect(cancelSpy).toHaveBeenCalled();
window.dispatchEvent(new Event('resize'));
expect(contexts).toHaveLength(3);
});
it('FE-LOGIN-WORLD-013: does nothing when the canvas has no 2D context', () => {
contextBudget = 0;
expect(() => render(<LoginWorld />)).not.toThrow();
expect(contexts).toHaveLength(0);
expect(queue).toHaveLength(0);
});
it('FE-LOGIN-WORLD-014: keeps animating routes when the offscreen layer cannot be built', () => {
contextBudget = 1;
render(<LoginWorld />);
runFrames(10);
const visible = contexts[0];
expect(visible.drawImage).not.toHaveBeenCalled();
expect(visible.clearRect).toHaveBeenCalledTimes(10);
expect(visible.stroke.mock.calls.length).toBeGreaterThan(0);
});
});
+945
View File
@@ -0,0 +1,945 @@
// FE-LOGIN-HOOK-001 to FE-LOGIN-HOOK-040
import React from 'react';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { renderHook, act, waitFor } from '../../../tests/helpers/render';
import { MemoryRouter, type MemoryRouterProps } from 'react-router-dom';
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores } from '../../../tests/helpers/store';
import { buildAppConfig } from '../../../tests/helpers/factories';
import { TranslationProvider } from '../../i18n/TranslationContext';
import { useAuthStore, type LoginResult } from '../../store/authStore';
import { useSettingsStore } from '../../store/settingsStore';
import { startAuthentication } from '@simplewebauthn/browser';
import { useLogin } from './useLogin';
const mockNavigate = vi.fn();
vi.mock('react-router-dom', async () => {
const actual = await vi.importActual<typeof import('react-router-dom')>('react-router-dom');
return { ...actual, useNavigate: () => mockNavigate };
});
vi.mock('@simplewebauthn/browser', () => ({ startAuthentication: vi.fn() }));
const CONFIG_CACHE_KEY = 'trek_app_config_cache';
type AuthActions = ReturnType<typeof useAuthStore.getState>;
type AuthOk = Awaited<ReturnType<AuthActions['completeMfaLogin']>>;
function authOk(user: Record<string, unknown> = {}): AuthOk {
return {
user: { id: 1, username: 'demo', email: 'demo@example.com', role: 'user', ...user },
token: 'tok',
} as unknown as AuthOk;
}
function makeAuthMocks() {
return {
login: vi.fn(async (_email: string, _password: string, _remember?: boolean): Promise<LoginResult> => authOk()),
register: vi.fn(async (_username: string, _email: string, _password: string, _invite?: string) => authOk()),
demoLogin: vi.fn(async () => authOk()),
completeMfaLogin: vi.fn(async (_token: string, _code: string, _remember?: boolean) => authOk()),
loadUser: vi.fn(async (_opts?: { silent?: boolean }) => {}),
};
}
let auth: ReturnType<typeof makeAuthMocks>;
const realLocation = window.location;
const origLanguages = navigator.languages;
function setSearch(search: string) {
Object.defineProperty(window, 'location', {
configurable: true,
writable: true,
value: { ...realLocation, pathname: '/login', href: 'http://localhost/login', search },
});
}
function setLanguages(languages: string[]) {
Object.defineProperty(navigator, 'languages', { configurable: true, value: languages });
}
function wrapperFor(entries: MemoryRouterProps['initialEntries'] = ['/login']) {
return function Wrapper({ children }: { children: React.ReactNode }) {
return (
<MemoryRouter initialEntries={entries}>
<TranslationProvider>{children}</TranslationProvider>
</MemoryRouter>
);
};
}
function renderLogin(entries?: MemoryRouterProps['initialEntries']) {
return renderHook(() => useLogin(), { wrapper: wrapperFor(entries) });
}
function formEvent() {
return { preventDefault: vi.fn() } as unknown as React.FormEvent<HTMLFormElement>;
}
/** Wait for the app-config probe to settle so the hook is in its steady state. */
async function ready(result: { current: ReturnType<typeof useLogin> }) {
await waitFor(() => expect(result.current.appConfig).not.toBeNull());
}
beforeEach(() => {
resetAllStores();
mockNavigate.mockClear();
vi.mocked(startAuthentication).mockReset();
setSearch('');
auth = makeAuthMocks();
useAuthStore.setState(auth);
});
afterEach(() => {
vi.useRealTimers();
Object.defineProperty(window, 'location', { configurable: true, writable: true, value: realLocation });
Object.defineProperty(navigator, 'languages', { configurable: true, value: origLanguages });
});
describe('useLogin — app config probe', () => {
it('FE-LOGIN-HOOK-001: exposes the fetched config and stays in login mode when users exist', async () => {
const { result } = renderLogin();
await ready(result);
expect(result.current.appConfig?.has_users).toBe(true);
expect(result.current.mode).toBe('login');
expect(result.current.showRegisterOption).toBe(true);
expect(result.current.oidcOnly).toBe(false);
});
it('FE-LOGIN-HOOK-002: switches to register on a fresh instance with no users', async () => {
server.use(
http.get('/api/auth/app-config', () => HttpResponse.json(buildAppConfig({ has_users: false }))),
);
const { result } = renderLogin();
await ready(result);
expect(result.current.mode).toBe('register');
});
it('FE-LOGIN-HOOK-003: caches the config so the next probe failure still has something to show', async () => {
const { unmount } = renderLogin();
await waitFor(() => expect(localStorage.getItem(CONFIG_CACHE_KEY)).not.toBeNull());
unmount();
server.use(http.get('/api/auth/app-config', () => HttpResponse.error()));
const { result } = renderLogin();
await ready(result);
expect(result.current.appConfig?.password_login).toBe(true);
});
it('FE-LOGIN-HOOK-004: survives a storage quota error while caching the config', async () => {
const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new Error('QuotaExceededError');
});
const { result } = renderLogin();
await ready(result);
expect(result.current.appConfig?.has_users).toBe(true);
setItem.mockRestore();
});
it('FE-LOGIN-HOOK-005: ignores a corrupt config cache', async () => {
localStorage.setItem(CONFIG_CACHE_KEY, '{not json');
server.use(http.get('/api/auth/app-config', () => HttpResponse.error()));
const getItem = vi.spyOn(Storage.prototype, 'getItem');
const { result } = renderLogin();
await waitFor(() => expect(getItem).toHaveBeenCalledWith(CONFIG_CACHE_KEY));
expect(result.current.appConfig).toBeNull();
getItem.mockRestore();
});
it('FE-LOGIN-HOOK-006: leaves the config null when the probe fails and nothing is cached', async () => {
server.use(http.get('/api/auth/app-config', () => HttpResponse.error()));
const getItem = vi.spyOn(Storage.prototype, 'getItem');
const { result } = renderLogin();
await waitFor(() => expect(getItem).toHaveBeenCalledWith(CONFIG_CACHE_KEY));
expect(result.current.appConfig).toBeNull();
expect(result.current.oidcOnly).toBeFalsy();
getItem.mockRestore();
});
it('FE-LOGIN-HOOK-007: sends the browser straight to the IdP when passwords are disabled', async () => {
server.use(
http.get('/api/auth/app-config', () =>
HttpResponse.json(buildAppConfig({ password_login: false, oidc_configured: true, oidc_login: true })),
),
);
const { result } = renderLogin();
await ready(result);
expect(result.current.oidcOnly).toBe(true);
await waitFor(() => expect(window.location.href).toBe('/api/auth/oidc/login'));
});
it('FE-LOGIN-HOOK-008: does not bounce back to the IdP right after a logout', async () => {
server.use(
http.get('/api/auth/app-config', () =>
HttpResponse.json(buildAppConfig({ password_login: false, oidc_configured: true, oidc_login: true })),
),
);
const { result } = renderLogin([{ pathname: '/login', state: { noRedirect: true } }]);
await ready(result);
expect(result.current.noRedirect).toBe(true);
expect(window.location.href).toBe('http://localhost/login');
});
it('FE-LOGIN-HOOK-009: never auto-redirects on a cached config', async () => {
localStorage.setItem(
CONFIG_CACHE_KEY,
JSON.stringify(buildAppConfig({ password_login: false, oidc_configured: true, oidc_login: true })),
);
server.use(http.get('/api/auth/app-config', () => HttpResponse.error()));
const { result } = renderLogin();
await ready(result);
expect(result.current.oidcOnly).toBe(true);
expect(window.location.href).toBe('http://localhost/login');
});
});
describe('useLogin — redirect target', () => {
it('FE-LOGIN-HOOK-010: stashes a relative redirect for the round trip through the IdP', async () => {
setSearch('?redirect=%2Foauth%2Fconsent%3Fclient_id%3Dfoo');
const { result } = renderLogin();
await ready(result);
expect(sessionStorage.getItem('oidc_redirect')).toBe('/oauth/consent?client_id=foo');
});
it('FE-LOGIN-HOOK-011: rejects a protocol-relative redirect', async () => {
setSearch('?redirect=//evil.example.com/steal');
const { result } = renderLogin();
await ready(result);
expect(sessionStorage.getItem('oidc_redirect')).toBeNull();
});
it('FE-LOGIN-HOOK-012: rejects a backslash-escaped redirect', async () => {
setSearch('?redirect=/\\evil.example.com');
const { result } = renderLogin();
await ready(result);
expect(sessionStorage.getItem('oidc_redirect')).toBeNull();
});
it('FE-LOGIN-HOOK-013: rejects an absolute redirect', async () => {
setSearch('?redirect=https%3A%2F%2Fevil.example.com');
const { result } = renderLogin();
await ready(result);
expect(sessionStorage.getItem('oidc_redirect')).toBeNull();
});
});
describe('useLogin — invite links', () => {
it('FE-LOGIN-HOOK-014: opens registration for a valid invite', async () => {
setSearch('?invite=abc123');
server.use(http.get('/api/auth/invite/:token', () => HttpResponse.json({ valid: true })));
const { result } = renderLogin();
await waitFor(() => expect(result.current.mode).toBe('register'));
expect(result.current.inviteToken).toBe('abc123');
await waitFor(() => expect(result.current.showRegisterOption).toBe(true));
});
it('FE-LOGIN-HOOK-015: reports an invite link the server rejects', async () => {
setSearch('?invite=expired');
server.use(
http.get('/api/auth/invite/:token', () => HttpResponse.json({ error: 'gone' }, { status: 410 })),
);
const { result } = renderLogin();
await waitFor(() => expect(result.current.error).toBe('Invalid or expired invite link'));
});
});
describe('useLogin — OIDC callback', () => {
it('FE-LOGIN-HOOK-016: navigates to the stashed redirect after a successful code exchange', async () => {
sessionStorage.setItem('oidc_redirect', '/oauth/consent?client_id=foo');
setSearch('?oidc_code=code-1');
server.use(http.get('/api/auth/oidc/exchange', () => HttpResponse.json({ token: 'tok' })));
const { result } = renderLogin();
await waitFor(() =>
expect(mockNavigate).toHaveBeenCalledWith('/oauth/consent?client_id=foo', { replace: true }),
);
expect(auth.loadUser).toHaveBeenCalled();
await waitFor(() => expect(result.current.isLoading).toBe(false));
});
it('FE-LOGIN-HOOK-055: exchanges the single-use code exactly once, even when the page re-renders', async () => {
let exchanges = 0;
setSearch('?oidc_code=code-once');
server.use(
http.get('/api/auth/oidc/exchange', () => {
exchanges += 1;
return HttpResponse.json({ token: 'tok' });
}),
);
renderLogin();
await waitFor(() => expect(mockNavigate).toHaveBeenCalledWith('/dashboard', { replace: true }));
// Switching language rebuilds `t`, which the callback effect depends on.
await act(async () => {
useSettingsStore.getState().setLanguageLocal('de');
});
await waitFor(() => expect(useSettingsStore.getState().settings.language).toBe('de'));
expect(exchanges).toBe(1);
expect(mockNavigate).toHaveBeenCalledTimes(1);
});
it('FE-LOGIN-HOOK-017: surfaces the error the exchange endpoint reports', async () => {
setSearch('?oidc_code=code-2');
server.use(http.get('/api/auth/oidc/exchange', () => HttpResponse.json({ error: 'State mismatch' })));
const { result } = renderLogin();
await waitFor(() => expect(result.current.error).toBe('State mismatch'));
expect(mockNavigate).not.toHaveBeenCalled();
});
it('FE-LOGIN-HOOK-018: falls back to a generic message when the exchange returns nothing useful', async () => {
setSearch('?oidc_code=code-3');
server.use(http.get('/api/auth/oidc/exchange', () => HttpResponse.json({})));
const { result } = renderLogin();
await waitFor(() => expect(result.current.error).toBe('OIDC login failed'));
});
it('FE-LOGIN-HOOK-019: reports a generic failure when the exchange request itself fails', async () => {
setSearch('?oidc_code=code-4');
server.use(http.get('/api/auth/oidc/exchange', () => HttpResponse.error()));
const { result } = renderLogin();
await waitFor(() => expect(result.current.error).toBe('OIDC login failed'));
await waitFor(() => expect(result.current.isLoading).toBe(false));
});
it('FE-LOGIN-HOOK-020: translates a known oidc_error code and clears the stashed redirect', async () => {
sessionStorage.setItem('oidc_redirect', '/oauth/consent');
setSearch('?oidc_error=registration_disabled');
const { result } = renderLogin();
await waitFor(() =>
expect(result.current.error).toBe('Registration is disabled. Contact your administrator.'),
);
expect(sessionStorage.getItem('oidc_redirect')).toBeNull();
});
it('FE-LOGIN-HOOK-021: passes an unknown oidc_error through unchanged', async () => {
setSearch('?oidc_error=some_new_provider_code');
const { result } = renderLogin();
await waitFor(() => expect(result.current.error).toBe('some_new_provider_code'));
});
});
describe('useLogin — language detection', () => {
it('FE-LOGIN-HOOK-022: adopts the browser language when nothing is stored', async () => {
setLanguages(['de-DE', 'de']);
const { result } = renderLogin();
await ready(result);
expect(useSettingsStore.getState().settings.language).toBe('de');
});
it('FE-LOGIN-HOOK-023: falls back to the server default when the browser language is unsupported', async () => {
setLanguages(['xh-ZA']);
server.use(http.get('/api/config', () => HttpResponse.json({ defaultLanguage: 'fr' })));
const { result } = renderLogin();
await waitFor(() => expect(useSettingsStore.getState().settings.language).toBe('fr'));
await ready(result);
});
it('FE-LOGIN-HOOK-024: leaves the language alone when the server has no default either', async () => {
setLanguages(['xh-ZA']);
server.use(http.get('/api/config', () => HttpResponse.json({ defaultLanguage: '' })));
const { result } = renderLogin();
await ready(result);
expect(useSettingsStore.getState().settings.language).toBe('en');
});
it('FE-LOGIN-HOOK-025: warns instead of failing when the default-language probe errors', async () => {
setLanguages(['xh-ZA']);
server.use(http.get('/api/config', () => HttpResponse.error()));
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const { result } = renderLogin();
await waitFor(() =>
expect(warn).toHaveBeenCalledWith('Failed to fetch default language config:', expect.anything()),
);
await ready(result);
warn.mockRestore();
});
it('FE-LOGIN-HOOK-026: skips detection entirely when the user already picked a language', async () => {
localStorage.setItem('app_language', 'es');
setLanguages(['de-DE']);
const { result } = renderLogin();
await ready(result);
expect(useSettingsStore.getState().settings.language).toBe('en');
});
});
describe('useLogin — language dropdown', () => {
it('FE-LOGIN-HOOK-027: closes the dropdown on the next document click and stops listening once closed', async () => {
const { result } = renderLogin();
await ready(result);
act(() => result.current.setLangDropdownOpen(true));
expect(result.current.langDropdownOpen).toBe(true);
act(() => {
document.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
expect(result.current.langDropdownOpen).toBe(false);
// Listener is torn down — a second click cannot flip it back.
act(() => {
document.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
expect(result.current.langDropdownOpen).toBe(false);
});
});
describe('useLogin — demo login', () => {
it('FE-LOGIN-HOOK-028: takes off and navigates to the redirect target', async () => {
setSearch('?redirect=/trips/7');
const { result } = renderLogin();
await ready(result);
vi.useFakeTimers({ shouldAdvanceTime: true });
await act(async () => {
await result.current.handleDemoLogin();
});
expect(auth.demoLogin).toHaveBeenCalled();
expect(result.current.showTakeoff).toBe(true);
expect(result.current.isLoading).toBe(false);
act(() => {
vi.advanceTimersByTime(2600);
});
expect(mockNavigate).toHaveBeenCalledWith('/trips/7');
});
it('FE-LOGIN-HOOK-029: surfaces the demo failure message', async () => {
useAuthStore.setState({
demoLogin: vi.fn(async () => {
throw new Error('Demo is disabled');
}),
});
const { result } = renderLogin();
await ready(result);
await act(async () => {
await result.current.handleDemoLogin();
});
expect(result.current.error).toBe('Demo is disabled');
expect(result.current.showTakeoff).toBe(false);
});
it('FE-LOGIN-HOOK-030: falls back to a generic message when the rejection is not an Error', async () => {
useAuthStore.setState({
demoLogin: vi.fn(async () => {
throw 'nope';
}),
});
const { result } = renderLogin();
await ready(result);
await act(async () => {
await result.current.handleDemoLogin();
});
expect(result.current.error).toBe('Demo login failed');
});
});
describe('useLogin — passkey login', () => {
beforeEach(() => {
server.use(
http.post('/api/auth/passkey/login/options', () => HttpResponse.json({ challenge: 'chal' })),
http.post('/api/auth/passkey/login/verify', () => HttpResponse.json({ token: 'tok', user: {} })),
);
});
it('FE-LOGIN-HOOK-031: verifies the assertion, reloads the user and takes off', async () => {
vi.mocked(startAuthentication).mockResolvedValue({ id: 'cred-1' } as never);
const { result } = renderLogin();
await ready(result);
vi.useFakeTimers({ shouldAdvanceTime: true });
await act(async () => {
await result.current.handlePasskeyLogin();
});
expect(startAuthentication).toHaveBeenCalledWith({ optionsJSON: { challenge: 'chal' } });
expect(auth.loadUser).toHaveBeenCalledWith({ silent: true });
expect(result.current.showTakeoff).toBe(true);
act(() => {
vi.advanceTimersByTime(2600);
});
expect(mockNavigate).toHaveBeenCalledWith('/dashboard');
});
it.each(['NotAllowedError', 'AbortError'])(
'FE-LOGIN-HOOK-032: stays quiet when the native prompt is dismissed (%s)',
async (name) => {
const err = Object.assign(new Error('dismissed'), { name });
vi.mocked(startAuthentication).mockRejectedValue(err);
const { result } = renderLogin();
await ready(result);
await act(async () => {
await result.current.handlePasskeyLogin();
});
expect(result.current.error).toBe('');
expect(result.current.isLoading).toBe(false);
expect(result.current.showTakeoff).toBe(false);
},
);
it('FE-LOGIN-HOOK-033: reports a real passkey failure', async () => {
vi.mocked(startAuthentication).mockRejectedValue(new Error('Authenticator rejected the request'));
const { result } = renderLogin();
await ready(result);
await act(async () => {
await result.current.handlePasskeyLogin();
});
expect(result.current.error).toBe('Authenticator rejected the request');
expect(result.current.isLoading).toBe(false);
});
it('FE-LOGIN-HOOK-034: falls back to the generic passkey message for an opaque failure', async () => {
vi.mocked(startAuthentication).mockRejectedValue({ code: 17 });
const { result } = renderLogin();
await ready(result);
await act(async () => {
await result.current.handlePasskeyLogin();
});
expect(result.current.error).toBe('Passkey sign-in failed. Please try again.');
});
});
describe('useLogin — register submit', () => {
it('FE-LOGIN-HOOK-035: refuses an empty username', async () => {
const { result } = renderLogin();
await ready(result);
act(() => result.current.setMode('register'));
act(() => result.current.setUsername(' '));
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.error).toBe('Username is required');
expect(auth.register).not.toHaveBeenCalled();
expect(result.current.isLoading).toBe(false);
});
it('FE-LOGIN-HOOK-036: refuses a password below the minimum length', async () => {
const { result } = renderLogin();
await ready(result);
act(() => result.current.setMode('register'));
act(() => {
result.current.setUsername('newuser');
result.current.setPassword('short');
});
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.error).toBe('Password must be at least 8 characters');
expect(auth.register).not.toHaveBeenCalled();
});
it('FE-LOGIN-HOOK-037: registers with the invite token from the URL', async () => {
setSearch('?invite=inv-42');
server.use(http.get('/api/auth/invite/:token', () => HttpResponse.json({ valid: true })));
const { result } = renderLogin();
await waitFor(() => expect(result.current.inviteToken).toBe('inv-42'));
act(() => {
result.current.setUsername('newuser');
result.current.setEmail('new@example.com');
result.current.setPassword('password123');
});
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(auth.register).toHaveBeenCalledWith('newuser', 'new@example.com', 'password123', 'inv-42');
expect(result.current.showTakeoff).toBe(true);
});
it('FE-LOGIN-HOOK-038: registers without an invite token when there is none', async () => {
const { result } = renderLogin();
await ready(result);
act(() => result.current.setMode('register'));
act(() => {
result.current.setUsername('newuser');
result.current.setEmail('new@example.com');
result.current.setPassword('password123');
});
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(auth.register).toHaveBeenCalledWith('newuser', 'new@example.com', 'password123', undefined);
});
});
describe('useLogin — password submit', () => {
it('FE-LOGIN-HOOK-039: forwards the remember-me choice and takes off', async () => {
const { result } = renderLogin();
await ready(result);
act(() => {
result.current.setEmail('user@example.com');
result.current.setPassword('password123');
result.current.setRememberMe(true);
});
vi.useFakeTimers({ shouldAdvanceTime: true });
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(auth.login).toHaveBeenCalledWith('user@example.com', 'password123', true);
expect(result.current.showTakeoff).toBe(true);
act(() => {
vi.advanceTimersByTime(2600);
});
expect(mockNavigate).toHaveBeenCalledWith('/dashboard');
});
it('FE-LOGIN-HOOK-040: stops on a dropped Secure cookie instead of dead-ending later', async () => {
useAuthStore.setState({
login: vi.fn(async () => ({ ...authOk(), insecureCookie: true }) as unknown as LoginResult),
});
const { result } = renderLogin();
await ready(result);
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.insecureCookie).toBe(true);
expect(result.current.showTakeoff).toBe(false);
expect(result.current.isLoading).toBe(false);
});
it('FE-LOGIN-HOOK-041: moves to the MFA step when the server demands a second factor', async () => {
useAuthStore.setState({
login: vi.fn(async () => ({ mfa_required: true, mfa_token: 'mfa-tok' }) as unknown as LoginResult),
});
const { result } = renderLogin();
await ready(result);
act(() => result.current.setMfaCode('leftover'));
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.mfaStep).toBe(true);
expect(result.current.mfaToken).toBe('mfa-tok');
expect(result.current.mfaCode).toBe('');
expect(result.current.isLoading).toBe(false);
});
it('FE-LOGIN-HOOK-042: moves to the password-change step when the account is flagged', async () => {
useAuthStore.setState({
login: vi.fn(async () => authOk({ must_change_password: true }) as LoginResult),
});
const { result } = renderLogin();
await ready(result);
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.passwordChangeStep).toBe(true);
expect(result.current.showTakeoff).toBe(false);
});
it('FE-LOGIN-HOOK-043: surfaces the login error and stops the spinner', async () => {
useAuthStore.setState({
login: vi.fn(async () => {
throw new Error('Invalid credentials');
}),
});
const { result } = renderLogin();
await ready(result);
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.error).toBe('Invalid credentials');
expect(result.current.isLoading).toBe(false);
});
it('FE-LOGIN-HOOK-044: falls back to the generic login error for an opaque rejection', async () => {
useAuthStore.setState({
login: vi.fn(async () => {
throw { status: 500 };
}),
});
const { result } = renderLogin();
await ready(result);
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.error).toBe('Login failed. Please check your credentials.');
});
});
describe('useLogin — MFA step', () => {
async function reachMfaStep() {
useAuthStore.setState({
login: vi.fn(async () => ({ mfa_required: true, mfa_token: 'mfa-tok' }) as unknown as LoginResult),
});
const { result } = renderLogin();
await ready(result);
act(() => result.current.setPassword('password123'));
await act(async () => {
await result.current.handleSubmit(formEvent());
});
return result;
}
it('FE-LOGIN-HOOK-045: refuses a blank code', async () => {
const result = await reachMfaStep();
act(() => result.current.setMfaCode(' '));
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.error).toBe('Enter the code from your authenticator app.');
expect(auth.completeMfaLogin).not.toHaveBeenCalled();
});
it('FE-LOGIN-HOOK-046: verifies the code and takes off', async () => {
const result = await reachMfaStep();
act(() => {
result.current.setMfaCode('123456');
result.current.setRememberMe(true);
});
vi.useFakeTimers({ shouldAdvanceTime: true });
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(auth.completeMfaLogin).toHaveBeenCalledWith('mfa-tok', '123456', true);
expect(result.current.showTakeoff).toBe(true);
act(() => {
vi.advanceTimersByTime(2600);
});
expect(mockNavigate).toHaveBeenCalledWith('/dashboard');
});
it('FE-LOGIN-HOOK-047: hands over to the password-change step after MFA when the account is flagged', async () => {
useAuthStore.setState({
completeMfaLogin: vi.fn(async () => authOk({ must_change_password: true })),
});
const result = await reachMfaStep();
act(() => result.current.setMfaCode('123456'));
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.passwordChangeStep).toBe(true);
expect(result.current.showTakeoff).toBe(false);
expect(result.current.isLoading).toBe(false);
});
});
describe('useLogin — forced password change', () => {
async function reachPasswordChange() {
useAuthStore.setState({
login: vi.fn(async () => authOk({ must_change_password: true }) as LoginResult),
});
const { result } = renderLogin();
await ready(result);
act(() => result.current.setPassword('old-password'));
await act(async () => {
await result.current.handleSubmit(formEvent());
});
return result;
}
it('FE-LOGIN-HOOK-048: requires a new password', async () => {
const result = await reachPasswordChange();
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.error).toBe('Please enter current and new password');
expect(result.current.isLoading).toBe(false);
});
it('FE-LOGIN-HOOK-049: refuses a new password below the minimum length', async () => {
const result = await reachPasswordChange();
act(() => result.current.setNewPassword('short'));
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.error).toBe('Password must be at least 8 characters');
});
it('FE-LOGIN-HOOK-050: refuses a mismatched confirmation', async () => {
const result = await reachPasswordChange();
act(() => {
result.current.setNewPassword('newpassword123');
result.current.setConfirmPassword('newpassword124');
});
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.error).toBe('Passwords do not match');
});
it('FE-LOGIN-HOOK-051: submits the saved login password as the current one, then takes off', async () => {
let body: Record<string, unknown> | null = null;
server.use(
http.put('/api/auth/me/password', async ({ request }) => {
body = (await request.json()) as Record<string, unknown>;
return HttpResponse.json({ success: true });
}),
);
const result = await reachPasswordChange();
act(() => {
result.current.setNewPassword('newpassword123');
result.current.setConfirmPassword('newpassword123');
});
vi.useFakeTimers({ shouldAdvanceTime: true });
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(body).toEqual({ current_password: 'old-password', new_password: 'newpassword123' });
expect(auth.loadUser).toHaveBeenCalledWith({ silent: true });
expect(result.current.showTakeoff).toBe(true);
act(() => {
vi.advanceTimersByTime(2600);
});
expect(mockNavigate).toHaveBeenCalledWith('/dashboard');
});
it('FE-LOGIN-HOOK-052: surfaces a rejected password change', async () => {
server.use(
http.put('/api/auth/me/password', () =>
HttpResponse.json({ error: 'Current password is wrong' }, { status: 400 }),
),
);
const result = await reachPasswordChange();
act(() => {
result.current.setNewPassword('newpassword123');
result.current.setConfirmPassword('newpassword123');
});
await act(async () => {
await result.current.handleSubmit(formEvent());
});
expect(result.current.error).toBe('Current password is wrong');
expect(result.current.showTakeoff).toBe(false);
});
});
describe('useLogin — register visibility rules', () => {
it('FE-LOGIN-HOOK-053: hides registration once setup is complete and passwords are closed', async () => {
server.use(
http.get('/api/auth/app-config', () =>
HttpResponse.json({ ...buildAppConfig({ password_registration: false }), setup_complete: true }),
),
);
const { result } = renderLogin();
await ready(result);
expect(result.current.showRegisterOption).toBe(false);
});
it('FE-LOGIN-HOOK-054: still offers registration on a half-finished setup with no users', async () => {
server.use(
http.get('/api/auth/app-config', () =>
HttpResponse.json({
...buildAppConfig({ has_users: false, password_registration: false }),
setup_complete: false,
}),
),
);
const { result } = renderLogin();
await ready(result);
expect(result.current.showRegisterOption).toBe(true);
});
});
+57
View File
@@ -0,0 +1,57 @@
// FE-LOGIN-DOTS-001 to FE-LOGIN-DOTS-006
import { describe, it, expect } from 'vitest';
import { WORLD_GRID_H, WORLD_GRID_W, WORLD_LAT_BOT, WORLD_LAT_TOP, worldDots } from './worldDots';
describe('worldDots', () => {
it('FE-LOGIN-DOTS-001: exposes the grid the packed coastlines were baked against', () => {
expect(WORLD_GRID_W).toBe(300);
expect(WORLD_GRID_H).toBe(150);
expect(WORLD_LAT_TOP).toBe(80);
expect(WORLD_LAT_BOT).toBe(-58);
});
it('FE-LOGIN-DOTS-002: reads the first token as an absolute base36 cell index', () => {
const dots = worldDots();
// '1u' base36 = 66, and the next two tokens are +1 each.
expect(dots[0]).toEqual({ x: 66, y: 0 });
expect(dots[1]).toEqual({ x: 67, y: 0 });
expect(dots[2]).toEqual({ x: 68, y: 0 });
});
it('FE-LOGIN-DOTS-003: decodes one dot per packed token', () => {
expect(worldDots()).toHaveLength(7131);
});
it('FE-LOGIN-DOTS-004: keeps every dot inside the grid', () => {
const dots = worldDots();
for (const d of dots) {
expect(Number.isInteger(d.x)).toBe(true);
expect(Number.isInteger(d.y)).toBe(true);
expect(d.x).toBeGreaterThanOrEqual(0);
expect(d.x).toBeLessThan(WORLD_GRID_W);
expect(d.y).toBeGreaterThanOrEqual(0);
expect(d.y).toBeLessThan(WORLD_GRID_H);
}
});
it('FE-LOGIN-DOTS-005: yields strictly increasing cell indices, so the deltas never fold back', () => {
const dots = worldDots();
let previous = -1;
for (const d of dots) {
const index = d.y * WORLD_GRID_W + d.x;
expect(index).toBeGreaterThan(previous);
previous = index;
}
// Last cell of the bundle — the southern tip of South America.
expect(dots[dots.length - 1]).toEqual({ x: 128, y: 149 });
});
it('FE-LOGIN-DOTS-006: returns an independent array on every call', () => {
const first = worldDots();
const second = worldDots();
expect(first).not.toBe(second);
expect(first).toEqual(second);
first.length = 0;
expect(second.length).toBe(7131);
});
});
@@ -0,0 +1,187 @@
// FE-PAGE-RESET-001 to FE-PAGE-RESET-011
import { act, renderHook, waitFor } from '@testing-library/react';
import type { FormEvent } from 'react';
import { authApi } from '../../api/client';
import { useResetPassword } from './useResetPassword';
const navigate = vi.fn();
let search = new URLSearchParams('token=abc123');
vi.mock('react-router-dom', () => ({
useNavigate: () => navigate,
useSearchParams: () => [search],
}));
// The hook resolves its copy through the real translation context; the page
// renders it verbatim, so assertions go against the English strings.
vi.mock('../../i18n', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
const submitEvent = () => ({ preventDefault: vi.fn() }) as unknown as FormEvent;
/** Fills both password fields and submits. */
async function submit(result: { current: ReturnType<typeof useResetPassword> }, pw: string, pw2 = pw) {
act(() => { result.current.setPw(pw); result.current.setPw2(pw2); });
await act(() => result.current.handleSubmit(submitEvent()));
}
beforeEach(() => {
navigate.mockClear();
search = new URLSearchParams('token=abc123');
vi.spyOn(authApi, 'resetPassword').mockResolvedValue({ success: true } as never);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('useResetPassword', () => {
it('FE-PAGE-RESET-001: picks the token out of the query string', () => {
const { result } = renderHook(() => useResetPassword());
expect(result.current.token).toBe('abc123');
expect(result.current.error).toBe('');
expect(result.current.success).toBe(false);
});
it('FE-PAGE-RESET-002: complains immediately when the link carries no token', async () => {
search = new URLSearchParams();
const { result } = renderHook(() => useResetPassword());
await waitFor(() => expect(result.current.error).toBe('login.resetPasswordInvalidLink'));
});
it('FE-PAGE-RESET-003: refuses to submit without a token', async () => {
search = new URLSearchParams();
const { result } = renderHook(() => useResetPassword());
await submit(result, 'longenough1');
expect(authApi.resetPassword).not.toHaveBeenCalled();
});
it('FE-PAGE-RESET-004: rejects a password shorter than eight characters', async () => {
const { result } = renderHook(() => useResetPassword());
await submit(result, 'short1');
expect(result.current.error).toBe('login.passwordMinLength');
expect(authApi.resetPassword).not.toHaveBeenCalled();
});
it('FE-PAGE-RESET-005: rejects a mismatched confirmation', async () => {
const { result } = renderHook(() => useResetPassword());
await submit(result, 'longenough1', 'longenough2');
expect(result.current.error).toBe('login.passwordsDontMatch');
expect(authApi.resetPassword).not.toHaveBeenCalled();
});
it('FE-PAGE-RESET-006: sends token and password and reports success', async () => {
const { result } = renderHook(() => useResetPassword());
await submit(result, 'longenough1');
expect(authApi.resetPassword).toHaveBeenCalledWith({ token: 'abc123', new_password: 'longenough1' });
expect(result.current.success).toBe(true);
expect(result.current.isLoading).toBe(false);
});
it('FE-PAGE-RESET-007: switches to the MFA step-up when the server asks for a code', async () => {
vi.mocked(authApi.resetPassword).mockResolvedValueOnce({ mfa_required: true } as never);
const { result } = renderHook(() => useResetPassword());
await submit(result, 'longenough1');
expect(result.current.mfaRequired).toBe(true);
expect(result.current.success).toBe(false);
expect(result.current.isLoading).toBe(false);
});
it('FE-PAGE-RESET-008: sends the trimmed MFA code on the second attempt', async () => {
vi.mocked(authApi.resetPassword).mockResolvedValueOnce({ mfa_required: true } as never);
const { result } = renderHook(() => useResetPassword());
await submit(result, 'longenough1');
act(() => result.current.setMfaCode(' 123456 '));
await act(() => result.current.handleSubmit(submitEvent()));
expect(authApi.resetPassword).toHaveBeenLastCalledWith({
token: 'abc123', new_password: 'longenough1', mfa_code: '123456',
});
expect(result.current.success).toBe(true);
});
it('FE-PAGE-RESET-009: omits the MFA field while the code is still empty', async () => {
vi.mocked(authApi.resetPassword).mockResolvedValueOnce({ mfa_required: true } as never);
const { result } = renderHook(() => useResetPassword());
await submit(result, 'longenough1');
await act(() => result.current.handleSubmit(submitEvent()));
expect(authApi.resetPassword).toHaveBeenLastCalledWith({ token: 'abc123', new_password: 'longenough1' });
});
it('FE-PAGE-RESET-010: surfaces the server error message', async () => {
vi.mocked(authApi.resetPassword).mockRejectedValueOnce({
response: { data: { error: 'This link has expired' } },
});
const { result } = renderHook(() => useResetPassword());
await submit(result, 'longenough1');
expect(result.current.error).toBe('This link has expired');
expect(result.current.success).toBe(false);
});
it('FE-PAGE-RESET-011: surfaces a plain Error message as-is', async () => {
vi.mocked(authApi.resetPassword).mockRejectedValueOnce(new Error('Network Error'));
const { result } = renderHook(() => useResetPassword());
await submit(result, 'longenough1');
expect(result.current.error).toBe('Network Error');
});
it('FE-PAGE-RESET-011a: falls back to the generic copy for a throw without a message', async () => {
vi.mocked(authApi.resetPassword).mockRejectedValueOnce('nope');
const { result } = renderHook(() => useResetPassword());
await submit(result, 'longenough1');
expect(result.current.error).toBe('login.resetPasswordFailed');
});
it('FE-PAGE-RESET-012: leaves success off when the server neither succeeds nor asks for MFA', async () => {
vi.mocked(authApi.resetPassword).mockResolvedValueOnce({ success: false } as never);
const { result } = renderHook(() => useResetPassword());
await submit(result, 'longenough1');
expect(result.current.success).toBe(false);
expect(result.current.isLoading).toBe(false);
});
it('FE-PAGE-RESET-013: ignores a second submit while one is in flight', async () => {
let release: (() => void) | undefined;
vi.mocked(authApi.resetPassword).mockReturnValue(
new Promise(res => { release = () => res({ success: true } as never); }) as never,
);
const { result } = renderHook(() => useResetPassword());
act(() => { result.current.setPw('longenough1'); result.current.setPw2('longenough1'); });
let first: Promise<void>;
act(() => { first = result.current.handleSubmit(submitEvent()) as Promise<void>; });
expect(result.current.isLoading).toBe(true);
await act(() => result.current.handleSubmit(submitEvent()));
expect(authApi.resetPassword).toHaveBeenCalledTimes(1);
await act(async () => { release!(); await first; });
expect(result.current.success).toBe(true);
});
it('FE-PAGE-RESET-014: exposes the password visibility toggle', () => {
const { result } = renderHook(() => useResetPassword());
expect(result.current.showPw).toBe(false);
act(() => result.current.setShowPw(true));
expect(result.current.showPw).toBe(true);
});
});
File diff suppressed because it is too large Load Diff
+87
View File
@@ -0,0 +1,87 @@
// FE-REPO-ACCOM-001 to FE-REPO-ACCOM-006
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { accommodationRepo } from './accommodationRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import type { Accommodation } from '../types'
function buildAccommodation(overrides: Partial<Accommodation> = {}): Accommodation {
return {
id: 1,
trip_id: 16,
start_day_id: 1,
end_day_id: 2,
check_in: '15:00',
check_out: '11:00',
place_name: 'Hotel Central',
...overrides,
} as Accommodation
}
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
}
beforeEach(async () => {
await clearAll()
setOnline(true)
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('accommodationRepo.list', () => {
it('FE-REPO-ACCOM-001: online — returns REST accommodations and caches them', async () => {
const accommodation = buildAccommodation({ id: 81, trip_id: 16 })
server.use(http.get('/api/trips/16/accommodations', () => HttpResponse.json({ accommodations: [accommodation] })))
const result = await accommodationRepo.list(16)
expect(result.accommodations.map(a => a.id)).toEqual([81])
await new Promise(r => setTimeout(r, 0))
expect((await offlineDb.accommodations.get(81))!.place_name).toBe('Hotel Central')
})
it('FE-REPO-ACCOM-002: online — a payload without the array does not break the upsert', async () => {
server.use(http.get('/api/trips/16/accommodations', () => HttpResponse.json({})))
const result = await accommodationRepo.list(16)
expect(result.accommodations).toBeUndefined()
await new Promise(r => setTimeout(r, 0))
expect(await offlineDb.accommodations.count()).toBe(0)
})
it('FE-REPO-ACCOM-003: offline — returns only this trip\'s cached accommodations', async () => {
await offlineDb.accommodations.bulkPut([
buildAccommodation({ id: 82, trip_id: 16 }),
buildAccommodation({ id: 83, trip_id: 17 }),
])
setOnline(false)
const result = await accommodationRepo.list('16')
expect(result.accommodations.map(a => a.id)).toEqual([82])
})
it('FE-REPO-ACCOM-004: offline with an empty cache — returns an empty list', async () => {
setOnline(false)
expect((await accommodationRepo.list(404)).accommodations).toEqual([])
})
it('FE-REPO-ACCOM-005: a 500 is rethrown, not masked by the cache', async () => {
server.use(http.get('/api/trips/16/accommodations', () => HttpResponse.json({ error: 'boom' }, { status: 500 })))
await expect(accommodationRepo.list(16)).rejects.toThrow()
})
it('FE-REPO-ACCOM-006: a failing cache write does not break the online read', async () => {
vi.spyOn(offlineDb.accommodations, 'bulkPut').mockRejectedValue(new Error('quota exceeded'))
server.use(http.get('/api/trips/16/accommodations', () =>
HttpResponse.json({ accommodations: [buildAccommodation({ id: 84 })] })))
const result = await accommodationRepo.list(16)
expect(result.accommodations.map(a => a.id)).toEqual([84])
})
})
+55
View File
@@ -0,0 +1,55 @@
// FE-REPO-BUDGET-001 to FE-REPO-BUDGET-004
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { budgetRepo } from './budgetRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import { buildBudgetItem } from '../../tests/helpers/factories'
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
}
beforeEach(async () => {
await clearAll()
setOnline(true)
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('budgetRepo.list', () => {
it('FE-REPO-BUDGET-001: online — returns REST items and caches them', async () => {
const item = buildBudgetItem({ id: 61, trip_id: 12, name: 'Hotel', total_price: 420 })
server.use(http.get('/api/trips/12/budget', () => HttpResponse.json({ items: [item] })))
const result = await budgetRepo.list(12)
expect(result.items[0].total_price).toBe(420)
await new Promise(r => setTimeout(r, 0))
expect((await offlineDb.budgetItems.get(61))!.name).toBe('Hotel')
})
it('FE-REPO-BUDGET-002: offline — returns only this trip\'s cached items', async () => {
await offlineDb.budgetItems.bulkPut([
buildBudgetItem({ id: 62, trip_id: 12 }),
buildBudgetItem({ id: 63, trip_id: 13 }),
])
setOnline(false)
const result = await budgetRepo.list('12')
expect(result.items.map(i => i.id)).toEqual([62])
})
it('FE-REPO-BUDGET-003: offline with an empty cache — returns an empty list', async () => {
setOnline(false)
expect((await budgetRepo.list(404)).items).toEqual([])
})
it('FE-REPO-BUDGET-004: a 500 is rethrown, not masked by the cache', async () => {
server.use(http.get('/api/trips/12/budget', () => HttpResponse.json({ error: 'boom' }, { status: 500 })))
await expect(budgetRepo.list(12)).rejects.toThrow()
})
})
+59
View File
@@ -0,0 +1,59 @@
// FE-REPO-DAY-001 to FE-REPO-DAY-004
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { dayRepo } from './dayRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import { buildDay } from '../../tests/helpers/factories'
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
}
beforeEach(async () => {
await clearAll()
setOnline(true)
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('dayRepo.list', () => {
it('FE-REPO-DAY-001: online — returns REST days and caches them', async () => {
const days = [buildDay({ id: 11, trip_id: 5 }), buildDay({ id: 12, trip_id: 5 })]
server.use(http.get('/api/trips/5/days', () => HttpResponse.json({ days })))
const result = await dayRepo.list(5)
expect(result.days.map(d => d.id)).toEqual([11, 12])
await new Promise(r => setTimeout(r, 0))
expect(await offlineDb.days.where('trip_id').equals(5).count()).toBe(2)
})
it('FE-REPO-DAY-002: offline — returns the cached days sorted by day_number', async () => {
await offlineDb.days.bulkPut([
buildDay({ id: 21, trip_id: 5, day_number: 3 }),
buildDay({ id: 22, trip_id: 5, day_number: 1 }),
buildDay({ id: 23, trip_id: 5, day_number: 2 }),
buildDay({ id: 24, trip_id: 6, day_number: 1 }),
])
setOnline(false)
const result = await dayRepo.list('5')
expect(result.days.map(d => d.id)).toEqual([22, 23, 21])
})
it('FE-REPO-DAY-003: offline with an empty cache — returns an empty list', async () => {
setOnline(false)
expect((await dayRepo.list(404)).days).toEqual([])
})
it('FE-REPO-DAY-004: a 500 is rethrown, not masked by the cache', async () => {
await offlineDb.days.put(buildDay({ id: 31, trip_id: 5 }))
server.use(http.get('/api/trips/5/days', () => HttpResponse.json({ error: 'nope' }, { status: 500 })))
await expect(dayRepo.list(5)).rejects.toThrow()
})
})
+55
View File
@@ -0,0 +1,55 @@
// FE-REPO-FILE-001 to FE-REPO-FILE-004
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { fileRepo } from './fileRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import { buildTripFile } from '../../tests/helpers/factories'
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
}
beforeEach(async () => {
await clearAll()
setOnline(true)
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('fileRepo.list', () => {
it('FE-REPO-FILE-001: online — returns REST files and caches them', async () => {
const file = buildTripFile({ id: 41, trip_id: 7, original_name: 'booking.pdf' })
server.use(http.get('/api/trips/7/files', () => HttpResponse.json({ files: [file] })))
const result = await fileRepo.list(7)
expect(result.files.map(f => f.original_name)).toEqual(['booking.pdf'])
await new Promise(r => setTimeout(r, 0))
expect((await offlineDb.tripFiles.get(41))!.original_name).toBe('booking.pdf')
})
it('FE-REPO-FILE-002: offline — returns only this trip\'s cached files', async () => {
await offlineDb.tripFiles.bulkPut([
buildTripFile({ id: 42, trip_id: 7 }),
buildTripFile({ id: 43, trip_id: 8 }),
])
setOnline(false)
const result = await fileRepo.list('7')
expect(result.files.map(f => f.id)).toEqual([42])
})
it('FE-REPO-FILE-003: offline with an empty cache — returns an empty list', async () => {
setOnline(false)
expect((await fileRepo.list(404)).files).toEqual([])
})
it('FE-REPO-FILE-004: a 403 is rethrown so the caller can show the error', async () => {
server.use(http.get('/api/trips/7/files', () => HttpResponse.json({ error: 'forbidden' }, { status: 403 })))
await expect(fileRepo.list(7)).rejects.toThrow()
})
})
+109
View File
@@ -0,0 +1,109 @@
// FE-REPO-PACK-001 to FE-REPO-PACK-007
// Offline write paths — tests/unit/repo/packingRepo.test.ts covers the online ones.
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { packingRepo } from './packingRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import type { QueuedMutation } from '../db/offlineDb'
import { buildPackingItem } from '../../tests/helpers/factories'
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
}
async function queue(): Promise<QueuedMutation[]> {
return (await offlineDb.mutationQueue.toArray()).sort((a, b) => a.createdAt - b.createdAt)
}
beforeEach(async () => {
await clearAll()
setOnline(false)
})
afterEach(() => {
vi.restoreAllMocks()
setOnline(true)
})
describe('packingRepo.create — offline', () => {
it('FE-REPO-PACK-001: writes an unchecked optimistic row with a negative temp id', async () => {
const { item } = await packingRepo.create(4, { name: 'Rain jacket', quantity: 2 })
expect(item.id).toBeLessThan(0)
expect(item.trip_id).toBe(4)
expect(item.checked).toBe(0)
const cached = await offlineDb.packingItems.get(item.id)
expect(cached!.name).toBe('Rain jacket')
expect(cached!.quantity).toBe(2)
})
it('FE-REPO-PACK-002: enqueues a POST that carries the temp id', async () => {
const { item } = await packingRepo.create('4', { name: 'Towel' })
const [mutation] = await queue()
expect(mutation.method).toBe('POST')
expect(mutation.url).toBe('/trips/4/packing')
expect(mutation.resource).toBe('packingItems')
expect(mutation.tempId).toBe(item.id)
expect(mutation.body).toEqual({ name: 'Towel' })
})
it('FE-REPO-PACK-003: two same-millisecond creates get distinct temp ids', async () => {
const first = await packingRepo.create(4, { name: 'A' })
const second = await packingRepo.create(4, { name: 'B' })
expect(first.item.id).not.toBe(second.item.id)
expect(await offlineDb.packingItems.count()).toBe(2)
})
})
describe('packingRepo.update — offline', () => {
it('FE-REPO-PACK-004: merges into the cached row and sends the concurrency token', async () => {
const original = buildPackingItem({ id: 110, trip_id: 4, checked: 0, updated_at: '2026-04-04T00:00:00.000Z' })
await offlineDb.packingItems.put(original)
const { item } = await packingRepo.update(4, 110, { checked: 1 })
expect(item.checked).toBe(1)
expect(item.name).toBe(original.name)
const [mutation] = await queue()
expect(mutation.url).toBe('/trips/4/packing/110')
expect(mutation.entityId).toBe(110)
expect(mutation.baseUpdatedAt).toBe('2026-04-04T00:00:00.000Z')
})
it('FE-REPO-PACK-005: an unsynced item keeps the {id} placeholder url', async () => {
await offlineDb.packingItems.put(buildPackingItem({ id: -12, trip_id: 4 }))
await packingRepo.update(4, -12, { checked: 1 })
const [mutation] = await queue()
expect(mutation.url).toBe('/trips/4/packing/{id}')
expect(mutation.tempEntityId).toBe(-12)
expect(mutation.baseUpdatedAt).toBeNull()
})
})
describe('packingRepo.delete — offline', () => {
it('FE-REPO-PACK-006: removes the cached row and enqueues a DELETE', async () => {
await offlineDb.packingItems.put(buildPackingItem({ id: 111, trip_id: 4 }))
expect(await packingRepo.delete(4, 111)).toEqual({ success: true })
expect(await offlineDb.packingItems.get(111)).toBeUndefined()
const [mutation] = await queue()
expect(mutation.method).toBe('DELETE')
expect(mutation.url).toBe('/trips/4/packing/111')
expect(mutation.resource).toBe('packingItems')
})
it('FE-REPO-PACK-007: deleting an unsynced item keeps the {id} placeholder', async () => {
await offlineDb.packingItems.put(buildPackingItem({ id: -13, trip_id: 4 }))
await packingRepo.delete(4, -13)
const [mutation] = await queue()
expect(mutation.url).toBe('/trips/4/packing/{id}')
expect(mutation.tempEntityId).toBe(-13)
})
})
+206
View File
@@ -0,0 +1,206 @@
// FE-REPO-PLACE-001 to FE-REPO-PLACE-013
// Offline write paths (mutation queue + optimistic Dexie rows) and the bulk
// online paths, which tests/unit/repo/placeRepo.test.ts does not touch.
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { placeRepo } from './placeRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import type { QueuedMutation } from '../db/offlineDb'
import { buildPlace } from '../../tests/helpers/factories'
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
}
async function queue(): Promise<QueuedMutation[]> {
return (await offlineDb.mutationQueue.toArray()).sort((a, b) => a.createdAt - b.createdAt)
}
beforeEach(async () => {
await clearAll()
setOnline(false)
})
afterEach(() => {
vi.restoreAllMocks()
setOnline(true)
})
describe('placeRepo.create — offline', () => {
it('FE-REPO-PLACE-001: writes an optimistic row with a negative temp id', async () => {
const { place } = await placeRepo.create(3, { name: 'Sagrada Familia', lat: 41.4 })
expect(place.id).toBeLessThan(0)
expect(place.trip_id).toBe(3)
const cached = await offlineDb.places.get(place.id)
expect(cached!.name).toBe('Sagrada Familia')
})
it('FE-REPO-PLACE-002: enqueues a POST carrying the temp id for the later id rewrite', async () => {
const { place } = await placeRepo.create('3', { name: 'Park Güell' })
const [mutation] = await queue()
expect(mutation.method).toBe('POST')
expect(mutation.url).toBe('/trips/3/places')
expect(mutation.resource).toBe('places')
expect(mutation.tempId).toBe(place.id)
expect(mutation.status).toBe('pending')
expect(mutation.body).toEqual({ name: 'Park Güell' })
})
})
describe('placeRepo.update — offline', () => {
it('FE-REPO-PLACE-003: merges into the cached row and sends the concurrency token', async () => {
await offlineDb.places.put(buildPlace({ id: 90, trip_id: 3, name: 'Old', updated_at: '2026-01-01T00:00:00.000Z' }))
const { place } = await placeRepo.update(3, 90, { name: 'New' })
expect(place.name).toBe('New')
expect(place.trip_id).toBe(3)
const [mutation] = await queue()
expect(mutation.method).toBe('PUT')
expect(mutation.url).toBe('/trips/3/places/90')
expect(mutation.entityId).toBe(90)
expect(mutation.baseUpdatedAt).toBe('2026-01-01T00:00:00.000Z')
expect(mutation.tempEntityId).toBeUndefined()
})
it('FE-REPO-PLACE-004: an unsynced (negative id) target gets the {id} placeholder url', async () => {
await offlineDb.places.put(buildPlace({ id: -5, trip_id: 3 }))
await placeRepo.update(3, -5, { notes: 'later' })
const [mutation] = await queue()
expect(mutation.url).toBe('/trips/3/places/{id}')
expect(mutation.tempEntityId).toBe(-5)
})
it('FE-REPO-PLACE-005: nothing cached — still produces an optimistic row and a null token', async () => {
const { place } = await placeRepo.update(3, '91', { name: 'Ghost' })
expect(place).toEqual({ name: 'Ghost', id: 91 })
expect((await offlineDb.places.get(91))!.name).toBe('Ghost')
const [mutation] = await queue()
expect(mutation.baseUpdatedAt).toBeNull()
})
})
describe('placeRepo.delete — offline', () => {
it('FE-REPO-PLACE-006: removes the cached row and enqueues a DELETE', async () => {
await offlineDb.places.put(buildPlace({ id: 92, trip_id: 3 }))
expect(await placeRepo.delete(3, 92)).toEqual({ success: true })
expect(await offlineDb.places.get(92)).toBeUndefined()
const [mutation] = await queue()
expect(mutation.method).toBe('DELETE')
expect(mutation.url).toBe('/trips/3/places/92')
expect(mutation.body).toBeUndefined()
expect(mutation.entityId).toBe(92)
})
it('FE-REPO-PLACE-007: deleting an unsynced place keeps the {id} placeholder', async () => {
await offlineDb.places.put(buildPlace({ id: -7, trip_id: 3 }))
await placeRepo.delete(3, -7)
const [mutation] = await queue()
expect(mutation.url).toBe('/trips/3/places/{id}')
expect(mutation.tempEntityId).toBe(-7)
})
})
describe('placeRepo.deleteMany', () => {
it('FE-REPO-PLACE-008: offline — one DELETE per id, temp ids keep the placeholder', async () => {
await offlineDb.places.bulkPut([
buildPlace({ id: 93, trip_id: 3 }),
buildPlace({ id: -9, trip_id: 3 }),
])
const result = await placeRepo.deleteMany(3, [93, -9])
expect(result).toEqual({ deleted: [93, -9], count: 2 })
expect(await offlineDb.places.where('trip_id').equals(3).count()).toBe(0)
const mutations = await queue()
expect(mutations.map(m => m.url)).toEqual(['/trips/3/places/93', '/trips/3/places/{id}'])
expect(mutations[0].tempEntityId).toBeUndefined()
expect(mutations[1].tempEntityId).toBe(-9)
})
it('FE-REPO-PLACE-009: online — calls the bulk endpoint and drops the rows locally', async () => {
setOnline(true)
await offlineDb.places.bulkPut([buildPlace({ id: 94, trip_id: 3 }), buildPlace({ id: 95, trip_id: 3 })])
let body: unknown
server.use(http.post('/api/trips/3/places/bulk-delete', async ({ request }) => {
body = await request.json()
return HttpResponse.json({ deleted: [94, 95], count: 2 })
}))
const result = await placeRepo.deleteMany(3, [94, 95])
expect(result).toEqual({ deleted: [94, 95], count: 2 })
expect(body).toEqual({ ids: [94, 95] })
expect(await offlineDb.places.where('trip_id').equals(3).count()).toBe(0)
expect(await offlineDb.mutationQueue.count()).toBe(0)
})
})
describe('placeRepo.updateMany', () => {
it('FE-REPO-PLACE-010: offline — merges each cached row and fans out one PUT per id', async () => {
await offlineDb.places.bulkPut([
buildPlace({ id: 96, trip_id: 3, updated_at: '2026-02-02T00:00:00.000Z' }),
buildPlace({ id: 97, trip_id: 3, updated_at: '2026-03-03T00:00:00.000Z' }),
])
const result = await placeRepo.updateMany(3, [96, 97], { category_id: 4 })
expect(result).toEqual({ updated: [96, 97], count: 2 })
expect((await offlineDb.places.get(96))!.category_id).toBe(4)
expect((await offlineDb.places.get(97))!.category_id).toBe(4)
const mutations = await queue()
expect(mutations).toHaveLength(2)
expect(mutations.map(m => m.baseUpdatedAt)).toEqual(['2026-02-02T00:00:00.000Z', '2026-03-03T00:00:00.000Z'])
expect(mutations.every(m => m.method === 'PUT')).toBe(true)
})
it('FE-REPO-PLACE-011: offline — an uncached id is queued without inventing a local row', async () => {
const result = await placeRepo.updateMany(3, [-11], { notes: 'x' })
expect(result.count).toBe(1)
expect(await offlineDb.places.get(-11)).toBeUndefined()
const [mutation] = await queue()
expect(mutation.url).toBe('/trips/3/places/{id}')
expect(mutation.tempEntityId).toBe(-11)
expect(mutation.baseUpdatedAt).toBeNull()
})
it('FE-REPO-PLACE-012: online — calls the bulk endpoint and merges into the cached rows', async () => {
setOnline(true)
await offlineDb.places.bulkPut([buildPlace({ id: 98, trip_id: 3 }), buildPlace({ id: 99, trip_id: 3 })])
let body: unknown
server.use(http.post('/api/trips/3/places/bulk-update', async ({ request }) => {
body = await request.json()
return HttpResponse.json({ updated: [98, 99], count: 2 })
}))
const result = await placeRepo.updateMany(3, [98, 99], { category_id: 7 })
expect(result.count).toBe(2)
expect(body).toEqual({ ids: [98, 99], category_id: 7 })
expect((await offlineDb.places.get(98))!.category_id).toBe(7)
expect((await offlineDb.places.get(99))!.category_id).toBe(7)
})
it('FE-REPO-PLACE-013: online — ids missing from the cache are skipped on the merge', async () => {
setOnline(true)
await offlineDb.places.put(buildPlace({ id: 100, trip_id: 3 }))
server.use(http.post('/api/trips/3/places/bulk-update', () => HttpResponse.json({ updated: [100, 101], count: 2 })))
await placeRepo.updateMany(3, [100, 101], { category_id: 8 })
expect((await offlineDb.places.get(100))!.category_id).toBe(8)
expect(await offlineDb.places.get(101)).toBeUndefined()
})
})
+55
View File
@@ -0,0 +1,55 @@
// FE-REPO-RESV-001 to FE-REPO-RESV-004
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { reservationRepo } from './reservationRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import { buildReservation } from '../../tests/helpers/factories'
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
}
beforeEach(async () => {
await clearAll()
setOnline(true)
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('reservationRepo.list', () => {
it('FE-REPO-RESV-001: online — returns REST reservations and caches them', async () => {
const reservation = buildReservation({ id: 71, trip_id: 14, title: 'Sushi Bar' })
server.use(http.get('/api/trips/14/reservations', () => HttpResponse.json({ reservations: [reservation] })))
const result = await reservationRepo.list(14)
expect(result.reservations.map(r => r.title)).toEqual(['Sushi Bar'])
await new Promise(r => setTimeout(r, 0))
expect((await offlineDb.reservations.get(71))!.title).toBe('Sushi Bar')
})
it('FE-REPO-RESV-002: offline — returns only this trip\'s cached reservations', async () => {
await offlineDb.reservations.bulkPut([
buildReservation({ id: 72, trip_id: 14 }),
buildReservation({ id: 73, trip_id: 15 }),
])
setOnline(false)
const result = await reservationRepo.list('14')
expect(result.reservations.map(r => r.id)).toEqual([72])
})
it('FE-REPO-RESV-003: offline with an empty cache — returns an empty list', async () => {
setOnline(false)
expect((await reservationRepo.list(404)).reservations).toEqual([])
})
it('FE-REPO-RESV-004: a 500 is rethrown, not masked by the cache', async () => {
server.use(http.get('/api/trips/14/reservations', () => HttpResponse.json({ error: 'boom' }, { status: 500 })))
await expect(reservationRepo.list(14)).rejects.toThrow()
})
})
+55
View File
@@ -0,0 +1,55 @@
// FE-REPO-TODO-001 to FE-REPO-TODO-004
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { todoRepo } from './todoRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import { buildTodoItem } from '../../tests/helpers/factories'
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
}
beforeEach(async () => {
await clearAll()
setOnline(true)
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('todoRepo.list', () => {
it('FE-REPO-TODO-001: online — returns REST items and caches them', async () => {
const item = buildTodoItem({ id: 51, trip_id: 9, name: 'Book train' })
server.use(http.get('/api/trips/9/todo', () => HttpResponse.json({ items: [item] })))
const result = await todoRepo.list(9)
expect(result.items.map(i => i.name)).toEqual(['Book train'])
await new Promise(r => setTimeout(r, 0))
expect((await offlineDb.todoItems.get(51))!.name).toBe('Book train')
})
it('FE-REPO-TODO-002: offline — returns only this trip\'s cached items', async () => {
await offlineDb.todoItems.bulkPut([
buildTodoItem({ id: 52, trip_id: 9 }),
buildTodoItem({ id: 53, trip_id: 10 }),
])
setOnline(false)
const result = await todoRepo.list('9')
expect(result.items.map(i => i.id)).toEqual([52])
})
it('FE-REPO-TODO-003: offline with an empty cache — returns an empty list', async () => {
setOnline(false)
expect((await todoRepo.list(404)).items).toEqual([])
})
it('FE-REPO-TODO-004: a 500 is rethrown, not masked by the cache', async () => {
server.use(http.get('/api/trips/9/todo', () => HttpResponse.json({ error: 'boom' }, { status: 500 })))
await expect(todoRepo.list(9)).rejects.toThrow()
})
})
+99
View File
@@ -0,0 +1,99 @@
// FE-REPO-TRIP-001 to FE-REPO-TRIP-007
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { tripRepo } from './tripRepo'
import { offlineDb, clearAll } from '../db/offlineDb'
import { buildTrip } from '../../tests/helpers/factories'
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
}
beforeEach(async () => {
await clearAll()
setOnline(true)
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('tripRepo.list', () => {
it('FE-REPO-TRIP-001: online — merges active + archived and caches both in Dexie', async () => {
const active = buildTrip({ title: 'Lisbon' })
const archived = buildTrip({ title: 'Old Trip', is_archived: 1 })
server.use(
http.get('/api/trips', ({ request }) => {
const isArchived = new URL(request.url).searchParams.get('archived')
return HttpResponse.json({ trips: isArchived ? [archived] : [active] })
}),
)
const result = await tripRepo.list()
expect(result.trips.map(t => t.title)).toEqual(['Lisbon'])
expect(result.archivedTrips.map(t => t.title)).toEqual(['Old Trip'])
await new Promise(r => setTimeout(r, 0))
expect(await offlineDb.trips.get(active.id)).toBeDefined()
expect(await offlineDb.trips.get(archived.id)).toBeDefined()
})
it('FE-REPO-TRIP-002: offline — splits the Dexie cache by is_archived', async () => {
await offlineDb.trips.bulkPut([
buildTrip({ id: 71, is_archived: 0 }),
buildTrip({ id: 72, is_archived: 1 }),
])
setOnline(false)
let restCalled = false
server.use(http.get('/api/trips', () => { restCalled = true; return HttpResponse.json({ trips: [] }) }))
const result = await tripRepo.list()
expect(result.trips.map(t => t.id)).toEqual([71])
expect(result.archivedTrips.map(t => t.id)).toEqual([72])
expect(restCalled).toBe(false)
})
it('FE-REPO-TRIP-003: rethrows a server error instead of falling back to the cache', async () => {
await offlineDb.trips.put(buildTrip({ id: 73 }))
server.use(http.get('/api/trips', () => HttpResponse.json({ error: 'boom' }, { status: 500 })))
await expect(tripRepo.list()).rejects.toThrow()
})
})
describe('tripRepo.get', () => {
it('FE-REPO-TRIP-004: online — returns the trip and caches it', async () => {
const trip = buildTrip({ id: 80, title: 'Kyoto' })
server.use(http.get('/api/trips/80', () => HttpResponse.json({ trip })))
const result = await tripRepo.get(80)
expect(result.trip.title).toBe('Kyoto')
await new Promise(r => setTimeout(r, 0))
expect((await offlineDb.trips.get(80))!.title).toBe('Kyoto')
})
it('FE-REPO-TRIP-005: offline — serves the cached trip', async () => {
await offlineDb.trips.put(buildTrip({ id: 81, title: 'Cached' }))
setOnline(false)
const result = await tripRepo.get('81')
expect(result.trip.title).toBe('Cached')
})
it('FE-REPO-TRIP-006: offline with nothing cached — throws so the caller can show an error', async () => {
setOnline(false)
await expect(tripRepo.get(999)).rejects.toThrow('No cached trip data available offline')
})
it('FE-REPO-TRIP-007: network-level failure falls back to the cache (captive portal)', async () => {
await offlineDb.trips.put(buildTrip({ id: 82, title: 'Fallback' }))
server.use(http.get('/api/trips/82', () => HttpResponse.error()))
const result = await tripRepo.get(82)
expect(result.trip.title).toBe('Fallback')
})
})
+76
View File
@@ -0,0 +1,76 @@
// FE-W4WQ-001 to FE-W4WQ-005
import { describe, it, expect, vi, beforeEach } from 'vitest'
import type { WeatherResult } from '@trek/shared'
const get = vi.fn(async (_lat: number, _lng: number, _date: string) => ({} as WeatherResult))
vi.mock('../api/client', () => ({ weatherApi: { get: (lat: number, lng: number, date: string) => get(lat, lng, date) } }))
import { fetchWeather } from './weatherQueue'
function deferred() {
let resolve!: (v: WeatherResult) => void
let reject!: (e: unknown) => void
const promise = new Promise<WeatherResult>((res, rej) => { resolve = res; reject = rej })
return { promise, resolve, reject }
}
beforeEach(() => {
get.mockReset()
})
describe('fetchWeather', () => {
it('FE-W4WQ-001: forwards the coordinates and date to the api', async () => {
const result = { temp: 21 } as unknown as WeatherResult
get.mockResolvedValue(result)
await expect(fetchWeather(48.1, 11.5, '2026-06-15')).resolves.toBe(result)
expect(get).toHaveBeenCalledWith(48.1, 11.5, '2026-06-15')
})
it('FE-W4WQ-002: lets at most three requests run at once', async () => {
const gates = [deferred(), deferred(), deferred(), deferred()]
let started = 0
get.mockImplementation(() => { const g = gates[started]; started++; return g.promise })
const calls = gates.map((_, i) => fetchWeather(i, i, '2026-06-15'))
await Promise.resolve()
expect(started).toBe(3)
// Releasing one slot lets the queued fourth request start.
gates[0].resolve({} as WeatherResult)
await calls[0]
expect(started).toBe(4)
gates[1].resolve({} as WeatherResult)
gates[2].resolve({} as WeatherResult)
gates[3].resolve({} as WeatherResult)
await Promise.all(calls)
})
it('FE-W4WQ-003: releases the slot when a request rejects', async () => {
get.mockRejectedValueOnce(new Error('offline'))
await expect(fetchWeather(1, 1, '2026-06-15')).rejects.toThrow('offline')
get.mockResolvedValue({ ok: true } as unknown as WeatherResult)
await expect(fetchWeather(2, 2, '2026-06-16')).resolves.toEqual({ ok: true })
})
it('FE-W4WQ-004: drains a burst larger than the concurrency limit', async () => {
get.mockImplementation(async (lat: number) => ({ lat } as unknown as WeatherResult))
const results = await Promise.all(
Array.from({ length: 8 }, (_, i) => fetchWeather(i, i, '2026-06-15')),
)
expect(results.map(r => (r as unknown as { lat: number }).lat)).toEqual([0, 1, 2, 3, 4, 5, 6, 7])
expect(get).toHaveBeenCalledTimes(8)
})
it('FE-W4WQ-005: keeps accepting work after the queue has fully drained', async () => {
get.mockResolvedValue({ ok: true } as unknown as WeatherResult)
await Promise.all(Array.from({ length: 5 }, (_, i) => fetchWeather(i, i, '2026-06-15')))
await expect(fetchWeather(9, 9, '2026-06-20')).resolves.toEqual({ ok: true })
})
})
+829
View File
@@ -0,0 +1,829 @@
// FE-STORE-COLLECTION-001 to FE-STORE-COLLECTION-055
//
// The store owns the optimistic updates (status, labels, reorder, bulk delete) and the
// reload chains that follow every mutation, so the API layer is mocked here and the
// assertions are about resulting state + which endpoint got which arguments.
import { describe, it, expect, beforeEach, vi } from 'vitest'
import type {
Collection,
CollectionDetailResponse,
CollectionListResponse,
CollectionPlace,
} from '@trek/shared'
vi.mock('../api/collections', () => ({
collectionsApi: {
list: vi.fn(),
get: vi.fn(),
create: vi.fn(),
update: vi.fn(),
uploadCover: vi.fn(),
remove: vi.fn(),
reorder: vi.fn(),
savePlace: vi.fn(),
updatePlace: vi.fn(),
uploadPlaceImage: vi.fn(),
setStatus: vi.fn(),
ratePlace: vi.fn(),
deletePlace: vi.fn(),
deleteMany: vi.fn(),
copyToTrip: vi.fn(),
createLabel: vi.fn(),
updateLabel: vi.fn(),
deleteLabel: vi.fn(),
assignLabels: vi.fn(),
unassignLabels: vi.fn(),
invite: vi.fn(),
setMemberRole: vi.fn(),
acceptInvite: vi.fn(),
declineInvite: vi.fn(),
cancelInvite: vi.fn(),
removeMember: vi.fn(),
leave: vi.fn(),
},
}))
import { collectionsApi } from '../api/collections'
import { useCollectionStore, ALL_SAVED } from './collectionStore'
const listA: Collection = { id: 1, owner_id: 1, name: 'Tokyo' }
const listB: Collection = { id: 2, owner_id: 1, name: 'Kyoto' }
function buildPlace(over: Partial<CollectionPlace> = {}): CollectionPlace {
return { id: 10, collection_id: 1, name: 'Shibuya', status: 'want', ...over }
}
function detail(over: Partial<CollectionDetailResponse> = {}): CollectionDetailResponse {
return { collection: listA, places: [], ...over }
}
function listResponse(over: Partial<CollectionListResponse> = {}): CollectionListResponse {
return { collections: [listA], incomingInvites: [], ...over }
}
const store = () => useCollectionStore.getState()
const initialState = useCollectionStore.getState()
beforeEach(() => {
useCollectionStore.setState(initialState, true)
vi.clearAllMocks()
vi.mocked(collectionsApi.list).mockResolvedValue(listResponse())
vi.mocked(collectionsApi.get).mockResolvedValue(detail())
vi.mocked(collectionsApi.create).mockResolvedValue({ collection: listA })
vi.mocked(collectionsApi.update).mockResolvedValue({ collection: listA })
vi.mocked(collectionsApi.uploadCover).mockResolvedValue(listA)
vi.mocked(collectionsApi.remove).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.reorder).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.savePlace).mockResolvedValue({ place: buildPlace() })
vi.mocked(collectionsApi.updatePlace).mockResolvedValue(buildPlace())
vi.mocked(collectionsApi.uploadPlaceImage).mockResolvedValue(buildPlace())
vi.mocked(collectionsApi.setStatus).mockResolvedValue(buildPlace())
vi.mocked(collectionsApi.ratePlace).mockResolvedValue(buildPlace())
vi.mocked(collectionsApi.deletePlace).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.deleteMany).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.copyToTrip).mockResolvedValue({ copied: 0, skipped: [] })
vi.mocked(collectionsApi.createLabel).mockResolvedValue({ id: 3, collection_id: 1, name: 'Food' })
vi.mocked(collectionsApi.updateLabel).mockResolvedValue({ id: 3, collection_id: 1, name: 'Food' })
vi.mocked(collectionsApi.deleteLabel).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.assignLabels).mockResolvedValue({ changed: 1 })
vi.mocked(collectionsApi.unassignLabels).mockResolvedValue({ changed: 1 })
vi.mocked(collectionsApi.invite).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.setMemberRole).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.acceptInvite).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.declineInvite).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.cancelInvite).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.removeMember).mockResolvedValue({ success: true })
vi.mocked(collectionsApi.leave).mockResolvedValue({ success: true })
})
describe('collectionStore — loading', () => {
it('FE-STORE-COLLECTION-001: loadAll() stores collections and incoming invites', async () => {
vi.mocked(collectionsApi.list).mockResolvedValue(
listResponse({
collections: [listA, listB],
incomingInvites: [{ collection_id: 9, name: 'Osaka', from: { id: 4, username: 'bob' } }],
}),
)
await store().loadAll()
expect(store().collections).toEqual([listA, listB])
expect(store().incomingInvites[0].name).toBe('Osaka')
expect(store().loading).toBe(false)
})
it('FE-STORE-COLLECTION-002: loadAll() clears the loading flag even when the request fails', async () => {
vi.mocked(collectionsApi.list).mockRejectedValue(new Error('offline'))
await expect(store().loadAll()).rejects.toThrow('offline')
expect(store().loading).toBe(false)
expect(store().collections).toEqual([])
})
it('FE-STORE-COLLECTION-003: loadCollection() stores places, members and labels', async () => {
vi.mocked(collectionsApi.get).mockResolvedValue(
detail({
collection: {
...listA,
members: [{ user_id: 5, username: 'bob', status: 'accepted' }],
labels: [{ id: 3, collection_id: 1, name: 'Food' }],
},
places: [buildPlace()],
}),
)
await store().loadCollection(1)
expect(store().activeId).toBe(1)
expect(store().places).toHaveLength(1)
expect(store().members[0].username).toBe('bob')
expect(store().labels[0].name).toBe('Food')
expect(store().placesLoading).toBe(false)
})
it('FE-STORE-COLLECTION-004: loadCollection() falls back to empty members and labels', async () => {
vi.mocked(collectionsApi.get).mockResolvedValue(detail({ places: [buildPlace()] }))
await store().loadCollection(1)
expect(store().members).toEqual([])
expect(store().labels).toEqual([])
})
it('FE-STORE-COLLECTION-005: loadCollection() clears the active list when the fetch fails for it', async () => {
useCollectionStore.setState({ activeId: 1, places: [buildPlace()], members: [], labels: [] })
vi.mocked(collectionsApi.get).mockRejectedValue(new Error('403'))
await store().loadCollection(1)
expect(store().activeId).toBeNull()
expect(store().places).toEqual([])
expect(store().placesLoading).toBe(false)
})
it('FE-STORE-COLLECTION-006: loadCollection() keeps state when a different list fails', async () => {
useCollectionStore.setState({ activeId: 2, places: [buildPlace()] })
vi.mocked(collectionsApi.get).mockRejectedValue(new Error('403'))
await store().loadCollection(1)
expect(store().activeId).toBe(2)
expect(store().places).toHaveLength(1)
})
})
describe('collectionStore — setActive', () => {
it('FE-STORE-COLLECTION-007: setActive(null) clears the list and the selection', async () => {
useCollectionStore.setState({
activeId: 1,
places: [buildPlace()],
members: [{ user_id: 5, username: 'bob', status: 'accepted' }],
labels: [{ id: 3, collection_id: 1, name: 'Food' }],
selectMode: true,
selectedIds: [10],
selectedPlaceId: 10,
labelFilter: [3],
})
await store().setActive(null)
expect(store().activeId).toBeNull()
expect(store().places).toEqual([])
expect(store().members).toEqual([])
expect(store().labels).toEqual([])
expect(store().selectMode).toBe(false)
expect(store().selectedIds).toEqual([])
expect(store().selectedPlaceId).toBeNull()
expect(store().labelFilter).toEqual([])
expect(collectionsApi.get).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-008: setActive(ALL_SAVED) unions every list, dedups and skips failures', async () => {
useCollectionStore.setState({ collections: [listA, listB, { id: 3, owner_id: 1, name: 'Nara' }] })
vi.mocked(collectionsApi.get).mockImplementation(async (id: number) => {
if (id === 1) return detail({ places: [buildPlace({ id: 10 }), buildPlace({ id: 11 })] })
if (id === 2) return detail({ places: [buildPlace({ id: 11 }), buildPlace({ id: 12 })] })
throw new Error('403')
})
await store().setActive(ALL_SAVED)
expect(store().activeId).toBe(ALL_SAVED)
expect(store().places.map(p => p.id)).toEqual([10, 11, 12])
expect(store().members).toEqual([])
expect(store().placesLoading).toBe(false)
})
it('FE-STORE-COLLECTION-009: setActive(ALL_SAVED) loads the lists first when none are known yet', async () => {
vi.mocked(collectionsApi.list).mockResolvedValue(listResponse({ collections: [listB] }))
vi.mocked(collectionsApi.get).mockResolvedValue(detail({ places: [buildPlace({ id: 21 })] }))
await store().setActive(ALL_SAVED)
expect(collectionsApi.list).toHaveBeenCalled()
expect(collectionsApi.get).toHaveBeenCalledWith(2)
expect(store().places.map(p => p.id)).toEqual([21])
})
it('FE-STORE-COLLECTION-010: setActive(id) delegates to loadCollection', async () => {
vi.mocked(collectionsApi.get).mockResolvedValue(detail({ places: [buildPlace()] }))
await store().setActive(1)
expect(collectionsApi.get).toHaveBeenCalledWith(1)
expect(store().activeId).toBe(1)
})
it('FE-STORE-COLLECTION-011: refreshActive() is a no-op without an active list', async () => {
await store().refreshActive()
expect(collectionsApi.get).not.toHaveBeenCalled()
expect(collectionsApi.list).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-012: refreshActive() re-runs setActive for the current list', async () => {
useCollectionStore.setState({ activeId: 1 })
await store().refreshActive()
expect(collectionsApi.get).toHaveBeenCalledWith(1)
})
})
describe('collectionStore — list CRUD', () => {
it('FE-STORE-COLLECTION-013: createCollection() returns the new list and reloads', async () => {
const created = await store().createCollection({ name: 'Tokyo' })
expect(collectionsApi.create).toHaveBeenCalledWith({ name: 'Tokyo' })
expect(created).toEqual(listA)
expect(store().collections).toEqual([listA])
})
it('FE-STORE-COLLECTION-014: createCollection() returns null when the response carries no list', async () => {
vi.mocked(collectionsApi.create).mockResolvedValue({} as unknown as { collection: Collection })
expect(await store().createCollection({ name: 'Tokyo' })).toBeNull()
})
it('FE-STORE-COLLECTION-015: updateCollection() reloads the detail when the list is active', async () => {
useCollectionStore.setState({ activeId: 1 })
await store().updateCollection(1, { name: 'Tokyo 2026' })
expect(collectionsApi.update).toHaveBeenCalledWith(1, { name: 'Tokyo 2026' })
expect(collectionsApi.list).toHaveBeenCalled()
expect(collectionsApi.get).toHaveBeenCalledWith(1)
})
it('FE-STORE-COLLECTION-016: updateCollection() skips the detail reload for a non-active list', async () => {
useCollectionStore.setState({ activeId: 2 })
await store().updateCollection(1, { name: 'Tokyo 2026' })
expect(collectionsApi.get).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-017: uploadCover() sends the file as a "cover" form field', async () => {
useCollectionStore.setState({ activeId: 1 })
const file = new File(['x'], 'cover.jpg', { type: 'image/jpeg' })
await store().uploadCover(1, file)
const [id, fd] = vi.mocked(collectionsApi.uploadCover).mock.calls[0]
expect(id).toBe(1)
expect(fd.get('cover')).toBe(file)
expect(collectionsApi.get).toHaveBeenCalledWith(1)
})
it('FE-STORE-COLLECTION-017b: uploadCover() skips the detail reload for a non-active list', async () => {
useCollectionStore.setState({ activeId: 2 })
await store().uploadCover(1, new File(['x'], 'cover.jpg'))
expect(collectionsApi.uploadCover).toHaveBeenCalled()
expect(collectionsApi.list).toHaveBeenCalled()
expect(collectionsApi.get).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-018: deleteCollection() clears the active list before reloading', async () => {
useCollectionStore.setState({
activeId: 1,
places: [buildPlace()],
members: [{ user_id: 5, username: 'bob', status: 'accepted' }],
})
await store().deleteCollection(1)
expect(collectionsApi.remove).toHaveBeenCalledWith(1)
expect(store().activeId).toBeNull()
expect(store().places).toEqual([])
expect(store().members).toEqual([])
expect(collectionsApi.list).toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-019: deleteCollection() leaves another active list untouched', async () => {
useCollectionStore.setState({ activeId: 2, places: [buildPlace()] })
await store().deleteCollection(1)
expect(store().activeId).toBe(2)
expect(store().places).toHaveLength(1)
})
it('FE-STORE-COLLECTION-020: reorderCollections() applies the new order optimistically', async () => {
useCollectionStore.setState({ collections: [listA, listB] })
let orderDuringRequest: number[] = []
vi.mocked(collectionsApi.reorder).mockImplementation(async () => {
orderDuringRequest = store().collections.map(c => c.id)
return { success: true }
})
await store().reorderCollections([2, 1, 99])
expect(orderDuringRequest).toEqual([2, 1])
expect(collectionsApi.reorder).toHaveBeenCalledWith([2, 1, 99])
// the trailing loadAll re-syncs from the server
expect(store().collections).toEqual([listA])
})
it('FE-STORE-COLLECTION-021: reorderCollections() still reloads when the request fails', async () => {
useCollectionStore.setState({ collections: [listA, listB] })
vi.mocked(collectionsApi.reorder).mockRejectedValue(new Error('500'))
await expect(store().reorderCollections([2, 1])).rejects.toThrow('500')
expect(collectionsApi.list).toHaveBeenCalled()
})
})
describe('collectionStore — place mutations', () => {
it('FE-STORE-COLLECTION-022: setStatus() updates the place optimistically', async () => {
useCollectionStore.setState({ places: [buildPlace({ id: 10 }), buildPlace({ id: 11 })] })
await store().setStatus(10, 'visited')
expect(collectionsApi.setStatus).toHaveBeenCalledWith(10, 'visited')
expect(store().places[0].status).toBe('visited')
expect(store().places[1].status).toBe('want')
})
it('FE-STORE-COLLECTION-023: setStatus() re-reads the active list when the call fails', async () => {
useCollectionStore.setState({ activeId: 1, places: [buildPlace({ id: 10 })] })
vi.mocked(collectionsApi.setStatus).mockRejectedValue(new Error('500'))
vi.mocked(collectionsApi.get).mockResolvedValue(detail({ places: [buildPlace({ id: 10, status: 'want' })] }))
await store().setStatus(10, 'visited')
expect(collectionsApi.get).toHaveBeenCalledWith(1)
expect(store().places[0].status).toBe('want')
})
it('FE-STORE-COLLECTION-024: updatePlace() swaps in the place returned by the server', async () => {
useCollectionStore.setState({ places: [buildPlace({ id: 10 }), buildPlace({ id: 11 })] })
vi.mocked(collectionsApi.updatePlace).mockResolvedValue(buildPlace({ id: 10, name: 'Shibuya Sky' }))
await store().updatePlace(10, { name: 'Shibuya Sky' })
expect(store().places[0].name).toBe('Shibuya Sky')
expect(store().places[1].name).toBe('Shibuya')
})
it('FE-STORE-COLLECTION-025: updatePlace() leaves the list alone when nothing comes back', async () => {
useCollectionStore.setState({ places: [buildPlace({ id: 10 })] })
vi.mocked(collectionsApi.updatePlace).mockResolvedValue(undefined as unknown as CollectionPlace)
await store().updatePlace(10, { notes: 'x' })
expect(store().places).toEqual([buildPlace({ id: 10 })])
})
it('FE-STORE-COLLECTION-026: uploadPlaceImage() sends an "image" form field and swaps the place', async () => {
useCollectionStore.setState({ places: [buildPlace({ id: 10 }), buildPlace({ id: 11 })] })
const file = new File(['x'], 'p.jpg', { type: 'image/jpeg' })
vi.mocked(collectionsApi.uploadPlaceImage).mockResolvedValue(buildPlace({ id: 10, image_url: '/uploads/p.jpg' }))
await store().uploadPlaceImage(10, file)
const [pid, fd] = vi.mocked(collectionsApi.uploadPlaceImage).mock.calls[0]
expect(pid).toBe(10)
expect(fd.get('image')).toBe(file)
expect(store().places[0].image_url).toBe('/uploads/p.jpg')
expect(store().places[1].image_url).toBeUndefined()
})
it('FE-STORE-COLLECTION-026b: uploadPlaceImage() keeps the list when the server returns nothing', async () => {
useCollectionStore.setState({ places: [buildPlace({ id: 10 })] })
vi.mocked(collectionsApi.uploadPlaceImage).mockResolvedValue(undefined as unknown as CollectionPlace)
await store().uploadPlaceImage(10, new File(['x'], 'p.jpg'))
expect(store().places).toEqual([buildPlace({ id: 10 })])
})
it('FE-STORE-COLLECTION-027: ratePlace() swaps in the re-aggregated place', async () => {
useCollectionStore.setState({ places: [buildPlace({ id: 10 }), buildPlace({ id: 11 })] })
vi.mocked(collectionsApi.ratePlace).mockResolvedValue(buildPlace({ id: 10, rating_avg: 4.5, rating_count: 2 }))
await store().ratePlace(10, 5)
expect(collectionsApi.ratePlace).toHaveBeenCalledWith(10, 5)
expect(store().places[0].rating_avg).toBe(4.5)
expect(store().places[1].rating_avg).toBeUndefined()
})
it('FE-STORE-COLLECTION-028: ratePlace() keeps the list when the server returns nothing', async () => {
useCollectionStore.setState({ places: [buildPlace({ id: 10, rating_avg: 3 })] })
vi.mocked(collectionsApi.ratePlace).mockResolvedValue(undefined as unknown as CollectionPlace)
await store().ratePlace(10, null)
expect(store().places[0].rating_avg).toBe(3)
})
it('FE-STORE-COLLECTION-029: deletePlace() drops the place and refreshes the counts', async () => {
useCollectionStore.setState({ places: [buildPlace({ id: 10 }), buildPlace({ id: 11 })] })
await store().deletePlace(10)
expect(store().places.map(p => p.id)).toEqual([11])
expect(collectionsApi.deletePlace).toHaveBeenCalledWith(10)
expect(collectionsApi.list).toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-030: deleteMany() drops all selected places and exits select mode', async () => {
useCollectionStore.setState({
places: [buildPlace({ id: 10 }), buildPlace({ id: 11 }), buildPlace({ id: 12 })],
selectedIds: [10, 11],
selectMode: true,
})
await store().deleteMany([10, 11])
expect(store().places.map(p => p.id)).toEqual([12])
expect(store().selectedIds).toEqual([])
expect(store().selectMode).toBe(false)
expect(collectionsApi.deleteMany).toHaveBeenCalledWith([10, 11])
})
it('FE-STORE-COLLECTION-031: copyToTrip() forwards the payload and returns the dedup report', async () => {
vi.mocked(collectionsApi.copyToTrip).mockResolvedValue({ copied: 1, skipped: [{ id: 11, name: 'Shibuya' }] })
const res = await store().copyToTrip(7, [10, 11], true)
expect(collectionsApi.copyToTrip).toHaveBeenCalledWith({ trip_id: 7, place_ids: [10, 11], force: true })
expect(res.copied).toBe(1)
expect(res.skipped).toEqual([{ id: 11, name: 'Shibuya' }])
})
it('FE-STORE-COLLECTION-032: moveToList() re-points each place and reloads the active list', async () => {
useCollectionStore.setState({
activeId: 1,
places: [buildPlace({ id: 10 }), buildPlace({ id: 11 }), buildPlace({ id: 12 })],
selectedIds: [10, 11],
selectMode: true,
})
await store().moveToList([10, 11], 2)
expect(collectionsApi.updatePlace).toHaveBeenNthCalledWith(1, 10, { collection_id: 2 })
expect(collectionsApi.updatePlace).toHaveBeenNthCalledWith(2, 11, { collection_id: 2 })
expect(store().selectedIds).toEqual([])
expect(store().selectMode).toBe(false)
expect(collectionsApi.get).toHaveBeenCalledWith(1)
})
it('FE-STORE-COLLECTION-033: moveToList() skips the detail reload on the "All saved" pseudo-list', async () => {
useCollectionStore.setState({ activeId: ALL_SAVED, places: [buildPlace({ id: 10 })] })
await store().moveToList([10], 2)
expect(store().places).toEqual([])
expect(collectionsApi.get).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-034: duplicateToList() re-saves each place into the target list', async () => {
const source = buildPlace({
id: 10,
name: 'Shibuya Sky',
description: 'view',
lat: 35.6,
lng: 139.7,
address: 'Shibuya',
category_id: 4,
price: 2000,
currency: 'JPY',
notes: 'sunset',
image_url: '/uploads/p.jpg',
google_place_id: 'g1',
google_ftid: 'f1',
osm_id: 'o1',
website: 'https://example.com',
phone: '+81',
status: 'visited',
links: [{ url: 'https://example.com' }],
})
useCollectionStore.setState({ places: [source], selectedIds: [10], selectMode: true })
await store().duplicateToList([10], 2)
expect(collectionsApi.savePlace).toHaveBeenCalledWith({
collection_id: 2,
name: 'Shibuya Sky',
description: 'view',
lat: 35.6,
lng: 139.7,
address: 'Shibuya',
category_id: 4,
price: 2000,
currency: 'JPY',
notes: 'sunset',
image_url: '/uploads/p.jpg',
google_place_id: 'g1',
google_ftid: 'f1',
osm_id: 'o1',
website: 'https://example.com',
phone: '+81',
status: 'visited',
links: [{ url: 'https://example.com' }],
force: true,
})
expect(store().selectedIds).toEqual([])
expect(store().selectMode).toBe(false)
})
it('FE-STORE-COLLECTION-035: duplicateToList() normalises absent fields to null and skips unknown ids', async () => {
useCollectionStore.setState({ places: [buildPlace({ id: 10 })] })
await store().duplicateToList([10, 999], 2)
expect(collectionsApi.savePlace).toHaveBeenCalledTimes(1)
expect(collectionsApi.savePlace).toHaveBeenCalledWith(
expect.objectContaining({ collection_id: 2, description: null, lat: null, lng: null, links: [] }),
)
})
})
describe('collectionStore — labels', () => {
it('FE-STORE-COLLECTION-036: createLabel() is ignored without a real active list', async () => {
useCollectionStore.setState({ activeId: ALL_SAVED })
await store().createLabel('Food', '#ef4444')
expect(collectionsApi.createLabel).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-037: createLabel() posts to the active list and reloads it', async () => {
useCollectionStore.setState({ activeId: 1 })
await store().createLabel('Food', '#ef4444')
expect(collectionsApi.createLabel).toHaveBeenCalledWith(1, 'Food', '#ef4444')
expect(collectionsApi.get).toHaveBeenCalledWith(1)
})
it('FE-STORE-COLLECTION-038: updateLabel() recolors optimistically before the reload', async () => {
useCollectionStore.setState({
activeId: 1,
labels: [{ id: 3, collection_id: 1, name: 'Food', color: '#ef4444' }],
})
let optimistic: string | null | undefined
vi.mocked(collectionsApi.updateLabel).mockImplementation(async () => {
optimistic = store().labels[0].color
return { id: 3, collection_id: 1, name: 'Food', color: '#22c55e' }
})
await store().updateLabel(3, { color: '#22c55e' })
expect(optimistic).toBe('#22c55e')
expect(collectionsApi.get).toHaveBeenCalledWith(1)
})
it('FE-STORE-COLLECTION-039: updateLabel() skips the reload outside a real list', async () => {
useCollectionStore.setState({
activeId: ALL_SAVED,
labels: [{ id: 3, collection_id: 1, name: 'Food' }, { id: 4, collection_id: 1, name: 'Museum' }],
})
await store().updateLabel(3, { name: 'Eats' })
expect(store().labels[0].name).toBe('Eats')
expect(store().labels[1].name).toBe('Museum')
expect(collectionsApi.get).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-040: deleteLabel() drops the label, its filter and its assignments', async () => {
useCollectionStore.setState({
activeId: ALL_SAVED,
labels: [{ id: 3, collection_id: 1, name: 'Food' }, { id: 4, collection_id: 1, name: 'Museum' }],
labelFilter: [3, 4],
places: [buildPlace({ id: 10, label_ids: [3, 4] }), buildPlace({ id: 11 })],
})
await store().deleteLabel(3)
expect(store().labels.map(l => l.id)).toEqual([4])
expect(store().labelFilter).toEqual([4])
expect(store().places[0].label_ids).toEqual([4])
expect(store().places[1].label_ids).toEqual([])
expect(collectionsApi.deleteLabel).toHaveBeenCalledWith(3)
expect(collectionsApi.get).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-040b: deleteLabel() reloads the detail when a real list is open', async () => {
useCollectionStore.setState({ activeId: 1, labels: [{ id: 3, collection_id: 1, name: 'Food' }] })
await store().deleteLabel(3)
expect(collectionsApi.get).toHaveBeenCalledWith(1)
})
it('FE-STORE-COLLECTION-041: assignLabels() adds the labels to the selected places only', async () => {
useCollectionStore.setState({
activeId: 1,
places: [buildPlace({ id: 10, label_ids: [3] }), buildPlace({ id: 11 }), buildPlace({ id: 12 })],
})
// The trailing loadCollection() overwrites places, so read the optimistic
// state while the request is still in flight.
let optimistic: CollectionPlace[] = []
vi.mocked(collectionsApi.assignLabels).mockImplementation(async () => {
optimistic = store().places
return { changed: 1 }
})
await store().assignLabels([3, 4], [10, 12])
expect(optimistic[0].label_ids).toEqual([3, 4])
expect(optimistic[1].label_ids).toBeUndefined()
// a place with no labels yet starts from an empty set
expect(optimistic[2].label_ids).toEqual([3, 4])
expect(collectionsApi.assignLabels).toHaveBeenCalledWith([3, 4], [10, 12])
expect(collectionsApi.unassignLabels).not.toHaveBeenCalled()
expect(collectionsApi.get).toHaveBeenCalledWith(1)
})
it('FE-STORE-COLLECTION-042: assignLabels(remove) strips the labels and hits the unassign endpoint', async () => {
useCollectionStore.setState({
activeId: ALL_SAVED,
places: [buildPlace({ id: 10, label_ids: [3, 4] })],
})
await store().assignLabels([3], [10], true)
expect(store().places[0].label_ids).toEqual([4])
expect(collectionsApi.unassignLabels).toHaveBeenCalledWith([3], [10])
expect(collectionsApi.assignLabels).not.toHaveBeenCalled()
})
})
describe('collectionStore — members and invitations', () => {
it('FE-STORE-COLLECTION-043: invite() reloads the detail only for the active list', async () => {
useCollectionStore.setState({ activeId: 1 })
await store().invite(1, 5, 'editor')
expect(collectionsApi.invite).toHaveBeenCalledWith(1, 5, 'editor')
expect(collectionsApi.get).toHaveBeenCalledWith(1)
vi.mocked(collectionsApi.get).mockClear()
await store().invite(2, 6)
expect(collectionsApi.get).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-044: setMemberRole() reloads the detail only for the active list', async () => {
useCollectionStore.setState({ activeId: 1 })
await store().setMemberRole(1, 5, 'admin')
expect(collectionsApi.setMemberRole).toHaveBeenCalledWith(1, 5, 'admin')
expect(collectionsApi.get).toHaveBeenCalledWith(1)
vi.mocked(collectionsApi.get).mockClear()
await store().setMemberRole(2, 5, 'viewer')
expect(collectionsApi.get).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-045: acceptInvite() reloads the lists', async () => {
vi.mocked(collectionsApi.list).mockResolvedValue(listResponse({ collections: [listA, listB] }))
await store().acceptInvite(2)
expect(collectionsApi.acceptInvite).toHaveBeenCalledWith(2)
expect(store().collections).toHaveLength(2)
})
it('FE-STORE-COLLECTION-046: declineInvite() reloads the lists', async () => {
useCollectionStore.setState({
incomingInvites: [{ collection_id: 9, name: 'Osaka', from: { id: 4, username: 'bob' } }],
})
await store().declineInvite(9)
expect(collectionsApi.declineInvite).toHaveBeenCalledWith(9)
expect(store().incomingInvites).toEqual([])
})
it('FE-STORE-COLLECTION-047: cancelInvite() reloads the detail only for the active list', async () => {
useCollectionStore.setState({ activeId: 1 })
await store().cancelInvite(1, 5)
expect(collectionsApi.cancelInvite).toHaveBeenCalledWith(1, 5)
expect(collectionsApi.get).toHaveBeenCalledWith(1)
vi.mocked(collectionsApi.get).mockClear()
await store().cancelInvite(2, 5)
expect(collectionsApi.get).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-048: removeMember() reloads the detail only for the active list', async () => {
useCollectionStore.setState({ activeId: 1 })
await store().removeMember(1, 5)
expect(collectionsApi.removeMember).toHaveBeenCalledWith(1, 5)
expect(collectionsApi.get).toHaveBeenCalledWith(1)
vi.mocked(collectionsApi.get).mockClear()
await store().removeMember(2, 5)
expect(collectionsApi.get).not.toHaveBeenCalled()
})
it('FE-STORE-COLLECTION-049: leave() clears the list when it was the active one', async () => {
useCollectionStore.setState({
activeId: 1,
places: [buildPlace()],
members: [{ user_id: 5, username: 'bob', status: 'accepted' }],
})
vi.mocked(collectionsApi.list).mockResolvedValue(listResponse({ collections: [] }))
await store().leave(1)
expect(collectionsApi.leave).toHaveBeenCalledWith(1)
expect(store().activeId).toBeNull()
expect(store().places).toEqual([])
expect(store().members).toEqual([])
expect(store().collections).toEqual([])
})
it('FE-STORE-COLLECTION-050: leave() keeps a different active list open', async () => {
useCollectionStore.setState({ activeId: 2, places: [buildPlace()] })
await store().leave(1)
expect(store().activeId).toBe(2)
expect(store().places).toHaveLength(1)
})
})
describe('collectionStore — view state', () => {
it('FE-STORE-COLLECTION-051: the view, sort and search setters write straight through', () => {
store().setView('map')
store().setSortMode('name_asc')
store().setSearch('shibuya')
store().setSelectedPlaceId(10)
expect(store().view).toBe('map')
expect(store().sortMode).toBe('name_asc')
expect(store().search).toBe('shibuya')
expect(store().selectedPlaceId).toBe(10)
})
it('FE-STORE-COLLECTION-052: the filter setters write straight through', () => {
store().setStatusFilter('visited')
store().setCategoryFilter(4)
store().setRatingFilter(3)
store().setLabelFilter([3, 4])
expect(store().statusFilter).toBe('visited')
expect(store().categoryFilter).toBe(4)
expect(store().ratingFilter).toBe(3)
expect(store().labelFilter).toEqual([3, 4])
})
it('FE-STORE-COLLECTION-053: setSelectMode(false) also drops the current selection', () => {
useCollectionStore.setState({ selectedIds: [10, 11] })
store().setSelectMode(true)
expect(store().selectMode).toBe(true)
expect(store().selectedIds).toEqual([10, 11])
store().setSelectMode(false)
expect(store().selectMode).toBe(false)
expect(store().selectedIds).toEqual([])
})
it('FE-STORE-COLLECTION-054: toggleSelect() adds an unselected id and removes a selected one', () => {
store().toggleSelect(10)
store().toggleSelect(11)
expect(store().selectedIds).toEqual([10, 11])
store().toggleSelect(10)
expect(store().selectedIds).toEqual([11])
})
it('FE-STORE-COLLECTION-055: setSelectedIds() replaces and clearSelection() resets select mode', () => {
useCollectionStore.setState({ selectMode: true })
store().setSelectedIds([10, 11, 12])
expect(store().selectedIds).toEqual([10, 11, 12])
store().clearSelection()
expect(store().selectedIds).toEqual([])
expect(store().selectMode).toBe(false)
})
})
@@ -0,0 +1,204 @@
// FE-STORE-JGAL-001 to FE-STORE-JGAL-011
import { http, HttpResponse } from 'msw';
import { server } from '../../tests/helpers/msw/server';
import { journeyApi } from '../api/client';
import { captureVideoPoster } from '../utils/videoPoster';
import { useJourneyStore } from './journeyStore';
import type { GalleryPhoto, JourneyDetail, JourneyEntry, JourneyPhoto } from './journeyStore';
// The real capture needs a decoding <video> + canvas; jsdom has neither.
vi.mock('../utils/videoPoster', async (importOriginal) => {
const actual = await importOriginal<typeof import('../utils/videoPoster')>();
return { ...actual, captureVideoPoster: vi.fn() };
});
const initialState = useJourneyStore.getState();
function buildPhoto(over: Partial<JourneyPhoto> = {}): JourneyPhoto {
return {
id: 1, entry_id: 10, photo_id: 100, caption: null, sort_order: 0, shared: 0, created_at: 0,
provider: 'local', asset_id: null, owner_id: 1, file_path: null, thumbnail_path: null,
width: null, height: null, media_type: 'image', duration_ms: null,
...over,
};
}
function buildGalleryPhoto(over: Partial<GalleryPhoto> = {}): GalleryPhoto {
return {
id: 1, journey_id: 50, photo_id: 100, caption: null, shared: 0, sort_order: 0, created_at: 0,
provider: 'local', asset_id: null, owner_id: 1, file_path: null, thumbnail_path: null,
width: null, height: null, media_type: 'image', duration_ms: null,
...over,
};
}
function buildEntry(over: Partial<JourneyEntry> = {}): JourneyEntry {
return {
id: 10, journey_id: 50, author_id: 1, type: 'entry', title: 'Day 1', story: null,
entry_date: '2026-04-01', entry_time: null, location_name: null, location_lat: null,
location_lng: null, mood: null, weather: null, tags: [], pros_cons: null,
visibility: 'private', sort_order: 0, photos: [], created_at: 0, updated_at: 0,
...over,
};
}
function buildDetail(over: Partial<JourneyDetail> = {}): JourneyDetail {
return {
id: 50, user_id: 1, title: 'Japan', subtitle: null, cover_gradient: null, cover_image: null,
status: 'active', created_at: 0, updated_at: 0,
entries: [], gallery: [], trips: [], contributors: [],
stats: { entries: 0, photos: 0, places: 0 },
...over,
};
}
const imageFile = () => new File(['x'], 'shrine.jpg', { type: 'image/jpeg' });
const videoFile = () => new File(['x'], 'clip.mp4', { type: 'video/mp4' });
beforeEach(() => {
useJourneyStore.setState(initialState, true);
server.resetHandlers();
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('journeyStore gallery + photo links', () => {
// ── uploadGalleryPhotos ──────────────────────────────────────────────────
it('FE-STORE-JGAL-001: uploading an image appends it to the journey gallery', async () => {
useJourneyStore.setState({ current: buildDetail({ gallery: [buildGalleryPhoto({ id: 1 })] }) });
const added = buildGalleryPhoto({ id: 2, photo_id: 101 });
// MSW's XHR interceptor hangs on FormData bodies in jsdom — spy on the API layer.
const spy = vi.spyOn(journeyApi, 'uploadGalleryPhotos').mockResolvedValue({ photos: [added] });
const result = await useJourneyStore.getState().uploadGalleryPhotos(50, [imageFile()]);
expect(result.succeeded).toEqual([added]);
expect(result.failed).toEqual([]);
expect(spy.mock.calls[0][0]).toBe(50);
expect((spy.mock.calls[0][1] as FormData).get('photos')).toBeInstanceOf(File);
expect(useJourneyStore.getState().current?.gallery.map(p => p.id)).toEqual([1, 2]);
});
it('FE-STORE-JGAL-002: a video is uploaded with its poster frame and duration', async () => {
useJourneyStore.setState({ current: buildDetail() });
const poster = new Blob(['jpg'], { type: 'image/jpeg' });
vi.mocked(captureVideoPoster).mockResolvedValue({ poster, durationMs: 4200 });
const added = buildGalleryPhoto({ id: 3, media_type: 'video', duration_ms: 4200 });
const spy = vi.spyOn(journeyApi, 'uploadGalleryVideo').mockResolvedValue({ photos: [added] });
const result = await useJourneyStore.getState().uploadGalleryPhotos(50, [videoFile()]);
const fd = spy.mock.calls[0][1] as FormData;
expect(fd.get('video')).toBeInstanceOf(File);
expect(fd.get('poster')).toBeInstanceOf(Blob);
expect(fd.get('duration_ms')).toBe('4200');
expect(result.succeeded).toEqual([added]);
expect(useJourneyStore.getState().current?.gallery).toEqual([added]);
});
it('FE-STORE-JGAL-003: a video whose poster capture fails still uploads the raw file', async () => {
useJourneyStore.setState({ current: buildDetail() });
vi.mocked(captureVideoPoster).mockResolvedValue({ poster: null, durationMs: null });
const spy = vi.spyOn(journeyApi, 'uploadGalleryVideo').mockResolvedValue({});
const result = await useJourneyStore.getState().uploadGalleryPhotos(50, [videoFile()]);
const fd = spy.mock.calls[0][1] as FormData;
expect(fd.get('poster')).toBeNull();
expect(fd.get('duration_ms')).toBeNull();
expect(result.succeeded).toEqual([]);
expect(useJourneyStore.getState().current?.gallery).toEqual([]);
});
it('FE-STORE-JGAL-004: photos for a different journey are not merged into the open one', async () => {
useJourneyStore.setState({ current: buildDetail({ id: 50 }) });
vi.spyOn(journeyApi, 'uploadGalleryPhotos').mockResolvedValue({ photos: [buildGalleryPhoto({ id: 9 })] });
const result = await useJourneyStore.getState().uploadGalleryPhotos(99, [imageFile()]);
expect(result.succeeded).toHaveLength(1);
expect(useJourneyStore.getState().current?.gallery).toEqual([]);
});
it('FE-STORE-JGAL-005: a 4xx upload lands in failed without touching the gallery', async () => {
useJourneyStore.setState({ current: buildDetail() });
vi.spyOn(journeyApi, 'uploadGalleryPhotos').mockRejectedValue(
Object.assign(new Error('Unsupported'), { response: { status: 415 } }),
);
const file = imageFile();
const result = await useJourneyStore.getState().uploadGalleryPhotos(50, [file]);
expect(result.succeeded).toEqual([]);
expect(result.failed).toEqual([file]);
expect(useJourneyStore.getState().current?.gallery).toEqual([]);
});
it('FE-STORE-JGAL-006: upload progress is reported to the caller', async () => {
useJourneyStore.setState({ current: buildDetail() });
vi.spyOn(journeyApi, 'uploadGalleryPhotos').mockResolvedValue({ photos: [] });
const onProgress = vi.fn();
await useJourneyStore.getState().uploadGalleryPhotos(50, [imageFile()], { onProgress });
expect(onProgress).toHaveBeenCalledWith(expect.objectContaining({ done: 1, total: 1, failed: 0 }));
});
// ── unlinkPhoto ──────────────────────────────────────────────────────────
it('FE-STORE-JGAL-007: unlinking removes the photo from that entry only', async () => {
const entry = buildEntry({ id: 10, photos: [buildPhoto({ id: 1 }), buildPhoto({ id: 2 })] });
const other = buildEntry({ id: 11, photos: [buildPhoto({ id: 1, entry_id: 11 })] });
useJourneyStore.setState({ current: buildDetail({ entries: [entry, other] }) });
server.use(http.delete('/api/journeys/entries/10/photos/1', () => HttpResponse.json({})));
await useJourneyStore.getState().unlinkPhoto(10, 1);
const entries = useJourneyStore.getState().current!.entries;
expect(entries[0].photos.map(p => p.id)).toEqual([2]);
expect(entries[1].photos.map(p => p.id)).toEqual([1]);
});
it('FE-STORE-JGAL-008: unlinking without an open journey leaves the state untouched', async () => {
server.use(http.delete('/api/journeys/entries/10/photos/1', () => HttpResponse.json({})));
await useJourneyStore.getState().unlinkPhoto(10, 1);
expect(useJourneyStore.getState().current).toBeNull();
});
it('FE-STORE-JGAL-009: a rejected unlink keeps the photo attached', async () => {
const entry = buildEntry({ id: 10, photos: [buildPhoto({ id: 1 })] });
useJourneyStore.setState({ current: buildDetail({ entries: [entry] }) });
server.use(http.delete('/api/journeys/entries/10/photos/1', () => HttpResponse.json({}, { status: 403 })));
await expect(useJourneyStore.getState().unlinkPhoto(10, 1)).rejects.toBeTruthy();
expect(useJourneyStore.getState().current!.entries[0].photos).toHaveLength(1);
});
// ── deleteGalleryPhoto ───────────────────────────────────────────────────
it('FE-STORE-JGAL-010: deleting a gallery photo drops it from the gallery and every entry', async () => {
const entry = buildEntry({ id: 10, photos: [buildPhoto({ id: 1 }), buildPhoto({ id: 2 })] });
useJourneyStore.setState({
current: buildDetail({
entries: [entry],
gallery: [buildGalleryPhoto({ id: 1 }), buildGalleryPhoto({ id: 2 })],
}),
});
server.use(http.delete('/api/journeys/50/gallery/1', () => HttpResponse.json({})));
await useJourneyStore.getState().deleteGalleryPhoto(50, 1);
const state = useJourneyStore.getState().current!;
expect(state.gallery.map(p => p.id)).toEqual([2]);
expect(state.entries[0].photos.map(p => p.id)).toEqual([2]);
});
it('FE-STORE-JGAL-011: deleting a gallery photo without an open journey is a no-op', async () => {
server.use(http.delete('/api/journeys/50/gallery/1', () => HttpResponse.json({})));
await useJourneyStore.getState().deleteGalleryPhoto(50, 1);
expect(useJourneyStore.getState().current).toBeNull();
});
});
+91 -1
View File
@@ -1,13 +1,21 @@
// FE-STORE-BUDGET-001 to FE-STORE-BUDGET-011
// FE-STORE-BUDGET-001 to FE-STORE-BUDGET-016
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildBudgetItem } from '../../../tests/helpers/factories';
import { useTripStore } from '../tripStore';
let addToast: ReturnType<typeof vi.fn>;
beforeEach(() => {
resetAllStores();
server.resetHandlers();
addToast = vi.fn();
window.__addToast = addToast as unknown as typeof window.__addToast;
});
afterEach(() => {
delete window.__addToast;
});
describe('budgetSlice', () => {
@@ -173,5 +181,87 @@ describe('budgetSlice', () => {
await useTripStore.getState().reorderBudgetItems(1, [2, 1]);
// After failure, fresh list from server
expect(useTripStore.getState().budgetItems[0].id).toBe(freshItem.id);
expect(addToast).toHaveBeenCalledWith(expect.any(String), 'error', undefined);
});
it('FE-STORE-BUDGET-016: toggleBudgetMemberPaid tolerates an item that carries no members array', async () => {
const bare = buildBudgetItem({ id: 40, trip_id: 1 });
delete (bare as Partial<typeof bare>).members;
const other = buildBudgetItem({ id: 41, trip_id: 1, members: [{ user_id: 3, paid: 0, username: 'carol' }] });
seedStore(useTripStore, { budgetItems: [bare, other] });
server.use(
http.put('/api/trips/1/budget/40/members/3/paid', () => HttpResponse.json({ success: true, paid: true }))
);
await useTripStore.getState().toggleBudgetMemberPaid(1, 40, 3, true);
expect(useTripStore.getState().budgetItems[0].members).toEqual([]);
// The untouched item keeps its own members.
expect(useTripStore.getState().budgetItems[1].members?.[0]?.paid).toBe(0);
});
it('FE-STORE-BUDGET-012: updateBudgetItem throws the server message and keeps the item', async () => {
const existing = buildBudgetItem({ id: 30, trip_id: 1, name: 'Old' });
seedStore(useTripStore, { budgetItems: [existing] });
server.use(
http.put('/api/trips/1/budget/30', () =>
HttpResponse.json({ error: 'Budget is locked' }, { status: 403 })
)
);
await expect(
useTripStore.getState().updateBudgetItem(1, 30, { name: 'New' })
).rejects.toThrow('Budget is locked');
expect(useTripStore.getState().budgetItems[0].name).toBe('Old');
});
it('FE-STORE-BUDGET-013: reorderBudgetCategories regroups items and appends unlisted categories', async () => {
const food = buildBudgetItem({ id: 1, trip_id: 1, category: 'Food' });
const transport = buildBudgetItem({ id: 2, trip_id: 1, category: 'Transport' });
const food2 = buildBudgetItem({ id: 3, trip_id: 1, category: 'Food' });
// No category at all — grouped under the 'Other' bucket.
const uncategorised = buildBudgetItem({ id: 4, trip_id: 1, category: null });
seedStore(useTripStore, { budgetItems: [food, transport, food2, uncategorised] });
let sent: Record<string, unknown> = {};
server.use(
http.put('/api/trips/1/budget/reorder/categories', async ({ request }) => {
sent = await request.json() as Record<string, unknown>;
return HttpResponse.json({ success: true });
})
);
await useTripStore.getState().reorderBudgetCategories(1, ['Transport', 'Food']);
expect(sent).toEqual({ orderedCategories: ['Transport', 'Food'] });
expect(useTripStore.getState().budgetItems.map(i => i.id)).toEqual([2, 1, 3, 4]);
});
it('FE-STORE-BUDGET-014: reorderBudgetCategories ignores a category with no items', async () => {
const food = buildBudgetItem({ id: 1, trip_id: 1, category: 'Food' });
seedStore(useTripStore, { budgetItems: [food] });
server.use(
http.put('/api/trips/1/budget/reorder/categories', () => HttpResponse.json({ success: true }))
);
await useTripStore.getState().reorderBudgetCategories(1, ['Lodging', 'Food']);
expect(useTripStore.getState().budgetItems.map(i => i.id)).toEqual([1]);
});
it('FE-STORE-BUDGET-015: reorderBudgetCategories reloads the server order and notifies on failure', async () => {
const food = buildBudgetItem({ id: 1, trip_id: 1, category: 'Food' });
const transport = buildBudgetItem({ id: 2, trip_id: 1, category: 'Transport' });
seedStore(useTripStore, { budgetItems: [food, transport] });
server.use(
http.put('/api/trips/1/budget/reorder/categories', () =>
HttpResponse.json({ error: 'Reorder rejected' }, { status: 500 })
),
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [food, transport] }))
);
await useTripStore.getState().reorderBudgetCategories(1, ['Transport', 'Food']);
expect(useTripStore.getState().budgetItems.map(i => i.id)).toEqual([1, 2]);
expect(addToast).toHaveBeenCalledWith('Reorder rejected', 'error', undefined);
});
});
@@ -0,0 +1,141 @@
// FE-TSLICE-NOTES-001 to FE-TSLICE-NOTES-009 (error paths and empty-map paths of the day-notes slice)
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildDay, buildDayNote } from '../../../tests/helpers/factories';
import { useTripStore } from '../tripStore';
beforeEach(() => {
resetAllStores();
server.resetHandlers();
});
describe('dayNotesSlice', () => {
it('FE-TSLICE-NOTES-001: updateDayNotes throws the server message and leaves the day untouched', async () => {
seedStore(useTripStore, { days: [buildDay({ id: 1, trip_id: 1, notes: 'original' })] });
server.use(
http.put('/api/trips/1/days/1', () =>
HttpResponse.json({ error: 'Notes too long' }, { status: 422 }),
),
);
await expect(useTripStore.getState().updateDayNotes(1, 1, 'x'.repeat(10))).rejects.toThrow('Notes too long');
expect(useTripStore.getState().days[0].notes).toBe('original');
});
it('FE-TSLICE-NOTES-002: updateDayTitle throws the server message and leaves the title untouched', async () => {
seedStore(useTripStore, { days: [buildDay({ id: 1, trip_id: 1, title: 'Day one' })] });
server.use(
http.put('/api/trips/1/days/1', () =>
HttpResponse.json({ error: 'Title rejected' }, { status: 422 }),
),
);
await expect(useTripStore.getState().updateDayTitle(1, 1, 'New title')).rejects.toThrow('Title rejected');
expect(useTripStore.getState().days[0].title).toBe('Day one');
});
it('FE-TSLICE-NOTES-003: updateDayNotes matches the day by numeric id even for a string dayId', async () => {
seedStore(useTripStore, {
days: [buildDay({ id: 1, trip_id: 1 }), buildDay({ id: 2, trip_id: 1 })],
});
await useTripStore.getState().updateDayNotes(1, '2', 'Beach day');
expect(useTripStore.getState().days[0].notes).toBeNull();
expect(useTripStore.getState().days[1].notes).toBe('Beach day');
});
it('FE-TSLICE-NOTES-004: updateDayNote throws the server message and keeps the stored note', async () => {
const note = buildDayNote({ id: 10, day_id: 1, text: 'Original' });
seedStore(useTripStore, { dayNotes: { '1': [note] } });
server.use(
http.put('/api/trips/1/days/1/notes/10', () =>
HttpResponse.json({ error: 'Note is locked' }, { status: 403 }),
),
);
await expect(
useTripStore.getState().updateDayNote(1, 1, 10, { text: 'Changed' }),
).rejects.toThrow('Note is locked');
expect(useTripStore.getState().dayNotes['1'][0].text).toBe('Original');
});
it('FE-TSLICE-NOTES-005: moveDayNote is a no-op when the note is not on the source day', async () => {
const note = buildDayNote({ id: 10, day_id: 1 });
seedStore(useTripStore, { dayNotes: { '1': [note], '2': [] } });
let called = false;
server.use(
http.delete('/api/trips/1/days/1/notes/:noteId', () => {
called = true;
return HttpResponse.json({ success: true });
}),
);
await useTripStore.getState().moveDayNote(1, 1, 2, 999);
expect(called).toBe(false);
expect(useTripStore.getState().dayNotes['1']).toHaveLength(1);
expect(useTripStore.getState().dayNotes['2']).toHaveLength(0);
});
it('FE-TSLICE-NOTES-007: addDayNote seeds a fresh list for a day with no notes yet', async () => {
seedStore(useTripStore, { dayNotes: {} });
server.use(
http.post('/api/trips/1/days/4/notes', () =>
HttpResponse.json({ note: buildDayNote({ id: 12, day_id: 4, text: 'Check-in 15:00' }) }),
),
);
const created = await useTripStore.getState().addDayNote(1, 4, { text: 'Check-in 15:00' });
expect(created.id).toBe(12);
expect(useTripStore.getState().dayNotes['4'].map(n => n.id)).toEqual([12]);
});
it('FE-TSLICE-NOTES-008: addDayNote rolls the temp note back out of a fresh list on failure', async () => {
seedStore(useTripStore, { dayNotes: {} });
server.use(
http.post('/api/trips/1/days/4/notes', () =>
HttpResponse.json({ error: 'Note rejected' }, { status: 422 }),
),
);
await expect(useTripStore.getState().addDayNote(1, 4, { text: 'nope' })).rejects.toThrow('Note rejected');
expect(useTripStore.getState().dayNotes['4']).toEqual([]);
});
it('FE-TSLICE-NOTES-009: moveDayNote creates the target day list when it does not exist yet', async () => {
const note = buildDayNote({ id: 10, day_id: 1, text: 'Ferry' });
seedStore(useTripStore, { dayNotes: { '1': [note] } });
server.use(
http.post('/api/trips/1/days/5/notes', () =>
HttpResponse.json({ note: buildDayNote({ id: 13, day_id: 5, text: 'Ferry' }) }),
),
);
await useTripStore.getState().moveDayNote(1, 1, 5, 10);
expect(useTripStore.getState().dayNotes['1']).toEqual([]);
expect(useTripStore.getState().dayNotes['5'].map(n => n.id)).toEqual([13]);
});
it('FE-TSLICE-NOTES-006: moveDayNote carries text, time and icon over to the target day', async () => {
const note = buildDayNote({ id: 10, day_id: 1, text: 'Ferry', time: '08:15', icon: '⛴️' });
seedStore(useTripStore, { dayNotes: { '1': [note], '2': [] } });
let created: Record<string, unknown> = {};
server.use(
http.post('/api/trips/1/days/2/notes', async ({ request }) => {
created = await request.json() as Record<string, unknown>;
return HttpResponse.json({ note: buildDayNote({ id: 11, day_id: 2, text: 'Ferry', time: '08:15', icon: '⛴️' }) });
}),
);
await useTripStore.getState().moveDayNote(1, 1, 2, 10, 3);
expect(created).toMatchObject({ text: 'Ferry', time: '08:15', icon: '⛴️', sort_order: 3 });
expect(useTripStore.getState().dayNotes['1']).toHaveLength(0);
expect(useTripStore.getState().dayNotes['2'][0].id).toBe(11);
});
});
+180
View File
@@ -0,0 +1,180 @@
// FE-TSLICE-DAYS-001 to FE-TSLICE-DAYS-008 (whole-day reorder + insert, #589)
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildDay, buildReservation } from '../../../tests/helpers/factories';
import { useTripStore } from '../tripStore';
import type { Day } from '../../types';
beforeEach(() => {
resetAllStores();
server.resetHandlers();
});
function datedDays(): Day[] {
return [
buildDay({ id: 1, trip_id: 1, day_number: 1, date: '2025-06-01', title: 'Arrival' }),
buildDay({ id: 2, trip_id: 1, day_number: 2, date: '2025-06-02', title: 'Museums' }),
buildDay({ id: 3, trip_id: 1, day_number: 3, date: '2025-06-03', title: 'Departure' }),
];
}
describe('daysSlice', () => {
describe('reorderDays', () => {
it('FE-TSLICE-DAYS-001: optimistically renumbers days and pins the dates to their slots', async () => {
seedStore(useTripStore, { days: datedDays() });
let optimistic: Day[] = [];
server.use(
http.put('/api/trips/1/days/reorder', () => {
optimistic = useTripStore.getState().days;
return HttpResponse.json({ success: true });
}),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: datedDays() })),
);
await useTripStore.getState().reorderDays(1, [3, 1, 2]);
expect(optimistic.map(d => d.id)).toEqual([3, 1, 2]);
expect(optimistic.map(d => d.day_number)).toEqual([1, 2, 3]);
// Content moves across the slots; the dates stay pinned to the slots.
expect(optimistic.map(d => d.date)).toEqual(['2025-06-01', '2025-06-02', '2025-06-03']);
expect(optimistic[0].title).toBe('Departure');
});
it('FE-TSLICE-DAYS-002: sends the requested order and refreshes days plus bookings', async () => {
seedStore(useTripStore, { days: datedDays(), reservations: [] });
let sent: number[] = [];
const serverDays = [
buildDay({ id: 3, trip_id: 1, day_number: 1, date: '2025-06-01', title: 'Departure' }),
buildDay({ id: 1, trip_id: 1, day_number: 2, date: '2025-06-02', title: 'Arrival' }),
buildDay({ id: 2, trip_id: 1, day_number: 3, date: '2025-06-03', title: 'Museums' }),
];
server.use(
http.put('/api/trips/1/days/reorder', async ({ request }) => {
const body = await request.json() as { orderedIds: number[] };
sent = body.orderedIds;
return HttpResponse.json({ success: true });
}),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: serverDays })),
http.get('/api/trips/1/reservations', () =>
HttpResponse.json({ reservations: [buildReservation({ id: 77, trip_id: 1, title: 'Re-stamped' })] }),
),
);
await useTripStore.getState().reorderDays(1, [3, 1, 2]);
expect(sent).toEqual([3, 1, 2]);
expect(useTripStore.getState().days.map(d => d.id)).toEqual([3, 1, 2]);
expect(useTripStore.getState().reservations.map(r => r.title)).toEqual(['Re-stamped']);
});
it('FE-TSLICE-DAYS-003: an undated trip keeps each day carrying its own date', async () => {
const undated = [
buildDay({ id: 1, trip_id: 1, day_number: 1, date: null }),
buildDay({ id: 2, trip_id: 1, day_number: 2, date: null }),
];
seedStore(useTripStore, { days: undated });
let optimistic: Day[] = [];
server.use(
http.put('/api/trips/1/days/reorder', () => {
optimistic = useTripStore.getState().days;
return HttpResponse.json({ success: true });
}),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: undated })),
);
await useTripStore.getState().reorderDays(1, [2, 1]);
expect(optimistic.map(d => d.id)).toEqual([2, 1]);
expect(optimistic.every(d => d.date === null)).toBe(true);
});
it('FE-TSLICE-DAYS-004: ids that are not in the store are dropped from the optimistic list', async () => {
seedStore(useTripStore, { days: datedDays() });
let optimistic: Day[] = [];
server.use(
http.put('/api/trips/1/days/reorder', () => {
optimistic = useTripStore.getState().days;
return HttpResponse.json({ success: true });
}),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: datedDays() })),
);
await useTripStore.getState().reorderDays(1, [2, 999, 1, 3]);
expect(optimistic.map(d => d.id)).toEqual([2, 1, 3]);
});
it('FE-TSLICE-DAYS-005: rolls back to the previous order and throws the server message', async () => {
seedStore(useTripStore, { days: datedDays() });
server.use(
http.put('/api/trips/1/days/reorder', () =>
HttpResponse.json({ error: 'Reorder rejected' }, { status: 409 }),
),
);
await expect(useTripStore.getState().reorderDays(1, [3, 1, 2])).rejects.toThrow('Reorder rejected');
const days = useTripStore.getState().days;
expect(days.map(d => d.id)).toEqual([1, 2, 3]);
expect(days.map(d => d.title)).toEqual(['Arrival', 'Museums', 'Departure']);
});
});
describe('insertDay', () => {
it('FE-TSLICE-DAYS-006: appends a day, refreshes the list and returns the new day', async () => {
seedStore(useTripStore, { days: datedDays() });
const created = buildDay({ id: 4, trip_id: 1, day_number: 4, date: '2025-06-04' });
let body: Record<string, unknown> = {};
server.use(
http.post('/api/trips/1/days', async ({ request }) => {
body = await request.json() as Record<string, unknown>;
return HttpResponse.json({ day: created });
}),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: [...datedDays(), created] })),
);
const result = await useTripStore.getState().insertDay(1);
expect(result?.id).toBe(4);
expect(body.position).toBeUndefined();
expect(useTripStore.getState().days).toHaveLength(4);
});
it('FE-TSLICE-DAYS-007: forwards the 1-based insert position', async () => {
seedStore(useTripStore, { days: datedDays() });
const created = buildDay({ id: 5, trip_id: 1, day_number: 2, date: '2025-06-02' });
let body: Record<string, unknown> = {};
server.use(
http.post('/api/trips/1/days', async ({ request }) => {
body = await request.json() as Record<string, unknown>;
return HttpResponse.json({ day: created });
}),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: [datedDays()[0], created] })),
);
await useTripStore.getState().insertDay(1, 2);
expect(body.position).toBe(2);
expect(useTripStore.getState().days.map(d => d.id)).toEqual([1, 5]);
});
it('FE-TSLICE-DAYS-008: restores the day list and throws when the insert fails', async () => {
seedStore(useTripStore, { days: datedDays() });
server.use(
http.post('/api/trips/1/days', () =>
HttpResponse.json({ error: 'Trip is locked' }, { status: 403 }),
),
);
await expect(useTripStore.getState().insertDay(1, 2)).rejects.toThrow('Trip is locked');
expect(useTripStore.getState().days.map(d => d.id)).toEqual([1, 2, 3]);
});
});
});
@@ -1,13 +1,22 @@
// FE-STORE-PACKING-001 to FE-STORE-PACKING-002 (reorder, #969)
// FE-STORE-PACKING-003 to FE-STORE-PACKING-015 (three-tier sharing #858, mutation and error paths)
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildPackingItem } from '../../../tests/helpers/factories';
import { useTripStore } from '../tripStore';
let addToast: ReturnType<typeof vi.fn>;
beforeEach(() => {
resetAllStores();
server.resetHandlers();
addToast = vi.fn();
window.__addToast = addToast as unknown as typeof window.__addToast;
});
afterEach(() => {
delete window.__addToast;
});
describe('packingSlice', () => {
@@ -44,5 +53,233 @@ describe('packingSlice', () => {
const items = useTripStore.getState().packingItems;
expect(items[0].id).toBe(1);
expect(items[1].id).toBe(2);
expect(addToast).toHaveBeenCalledWith(expect.any(String), 'error', undefined);
});
it('FE-STORE-PACKING-003: updatePackingItem throws the server message and keeps the item', async () => {
const item = buildPackingItem({ id: 1, trip_id: 1, name: 'Tent' });
seedStore(useTripStore, { packingItems: [item] });
server.use(
http.put('/api/trips/1/packing/1', () =>
HttpResponse.json({ error: 'Item is locked' }, { status: 403 })
)
);
await expect(
useTripStore.getState().updatePackingItem(1, 1, { name: 'Tarp' })
).rejects.toThrow('Item is locked');
expect(useTripStore.getState().packingItems[0].name).toBe('Tent');
});
it('FE-STORE-PACKING-004: setPackingItemSharing sends the tier plus recipients and replaces the item', async () => {
const item = buildPackingItem({ id: 1, trip_id: 1, is_private: 0 });
seedStore(useTripStore, { packingItems: [item] });
let sent: Record<string, unknown> = {};
server.use(
http.put('/api/trips/1/packing/1/sharing', async ({ request }) => {
sent = await request.json() as Record<string, unknown>;
return HttpResponse.json({
item: { ...item, is_private: 1, recipients: [{ user_id: 4, username: 'ben' }] },
});
})
);
await useTripStore.getState().setPackingItemSharing(1, 1, 'shared', [4]);
expect(sent).toEqual({ visibility: 'shared', recipient_ids: [4] });
const stored = useTripStore.getState().packingItems[0];
expect(stored.is_private).toBe(1);
expect(stored.recipients).toEqual([{ user_id: 4, username: 'ben' }]);
});
it('FE-STORE-PACKING-005: setPackingItemSharing notifies and rethrows on failure', async () => {
const item = buildPackingItem({ id: 1, trip_id: 1, is_private: 0 });
seedStore(useTripStore, { packingItems: [item] });
server.use(
http.put('/api/trips/1/packing/1/sharing', () =>
HttpResponse.json({ error: 'Not the owner' }, { status: 403 })
)
);
await expect(
useTripStore.getState().setPackingItemSharing(1, 1, 'personal', [])
).rejects.toBeDefined();
expect(addToast).toHaveBeenCalledWith('Not the owner', 'error', undefined);
expect(useTripStore.getState().packingItems[0].is_private).toBe(0);
});
it('FE-STORE-PACKING-006: clonePackingItem appends the personal copy', async () => {
const item = buildPackingItem({ id: 1, trip_id: 1, name: 'Powerbank' });
seedStore(useTripStore, { packingItems: [item] });
server.use(
http.post('/api/trips/1/packing/1/clone', () =>
HttpResponse.json({ item: buildPackingItem({ id: 2, trip_id: 1, name: 'Powerbank', is_private: 1 }) })
)
);
await useTripStore.getState().clonePackingItem(1, 1);
expect(useTripStore.getState().packingItems.map(i => i.id)).toEqual([1, 2]);
});
it('FE-STORE-PACKING-007: clonePackingItem ignores a copy the socket echo already added', async () => {
const item = buildPackingItem({ id: 1, trip_id: 1 });
const clone = buildPackingItem({ id: 2, trip_id: 1, is_private: 1 });
seedStore(useTripStore, { packingItems: [item, clone] });
server.use(
http.post('/api/trips/1/packing/1/clone', () => HttpResponse.json({ item: clone }))
);
await useTripStore.getState().clonePackingItem(1, 1);
expect(useTripStore.getState().packingItems.map(i => i.id)).toEqual([1, 2]);
});
it('FE-STORE-PACKING-008: clonePackingItem notifies instead of throwing on failure', async () => {
const item = buildPackingItem({ id: 1, trip_id: 1 });
seedStore(useTripStore, { packingItems: [item] });
server.use(
http.post('/api/trips/1/packing/1/clone', () =>
HttpResponse.json({ error: 'Cannot copy' }, { status: 500 })
)
);
await expect(useTripStore.getState().clonePackingItem(1, 1)).resolves.toBeUndefined();
expect(addToast).toHaveBeenCalledWith('Cannot copy', 'error', undefined);
expect(useTripStore.getState().packingItems).toHaveLength(1);
});
it('FE-STORE-PACKING-009: addPackingContributor stores the item returned by the join', async () => {
const item = buildPackingItem({ id: 1, trip_id: 1, contributors: [] });
seedStore(useTripStore, { packingItems: [item] });
server.use(
http.post('/api/trips/1/packing/1/contributors', () =>
HttpResponse.json({
item: { ...item, contributors: [{ user_id: 7, username: 'kim', status: 'joined' }] },
})
)
);
await useTripStore.getState().addPackingContributor(1, 1);
expect(useTripStore.getState().packingItems[0].contributors).toEqual([
{ user_id: 7, username: 'kim', status: 'joined' },
]);
});
it('FE-STORE-PACKING-010: addPackingContributor notifies instead of throwing on failure', async () => {
const item = buildPackingItem({ id: 1, trip_id: 1, contributors: [] });
seedStore(useTripStore, { packingItems: [item] });
server.use(
http.post('/api/trips/1/packing/1/contributors', () =>
HttpResponse.json({ error: 'Already joined' }, { status: 409 })
)
);
await expect(useTripStore.getState().addPackingContributor(1, 1)).resolves.toBeUndefined();
expect(addToast).toHaveBeenCalledWith('Already joined', 'error', undefined);
expect(useTripStore.getState().packingItems[0].contributors).toEqual([]);
});
it('FE-STORE-PACKING-011: removePackingContributor stores the item returned by the leave', async () => {
const item = buildPackingItem({
id: 1,
trip_id: 1,
contributors: [{ user_id: 7, username: 'kim', status: 'joined' }],
});
seedStore(useTripStore, { packingItems: [item] });
server.use(
http.delete('/api/trips/1/packing/1/contributors/7', () =>
HttpResponse.json({ item: { ...item, contributors: [] } })
)
);
await useTripStore.getState().removePackingContributor(1, 1, 7);
expect(useTripStore.getState().packingItems[0].contributors).toEqual([]);
});
it('FE-STORE-PACKING-012: removePackingContributor notifies instead of throwing on failure', async () => {
const item = buildPackingItem({
id: 1,
trip_id: 1,
contributors: [{ user_id: 7, username: 'kim', status: 'joined' }],
});
seedStore(useTripStore, { packingItems: [item] });
server.use(
http.delete('/api/trips/1/packing/1/contributors/7', () =>
HttpResponse.json({ error: 'Not a contributor' }, { status: 404 })
)
);
await expect(useTripStore.getState().removePackingContributor(1, 1, 7)).resolves.toBeUndefined();
expect(addToast).toHaveBeenCalledWith('Not a contributor', 'error', undefined);
expect(useTripStore.getState().packingItems[0].contributors).toHaveLength(1);
});
it('FE-STORE-PACKING-014: add, update, toggle and delete only touch the targeted item', async () => {
const target = buildPackingItem({ id: 1, trip_id: 1, name: 'Tent', checked: 0 });
const sibling = buildPackingItem({ id: 2, trip_id: 1, name: 'Stove', checked: 0 });
seedStore(useTripStore, { packingItems: [target, sibling] });
server.use(
http.post('/api/trips/1/packing', () =>
HttpResponse.json({ item: buildPackingItem({ id: 3, trip_id: 1, name: 'Mat' }) })
),
http.put('/api/trips/1/packing/1', () =>
HttpResponse.json({ item: { ...target, name: 'Tarp', checked: 1 } })
),
http.delete('/api/trips/1/packing/3', () => HttpResponse.json({ success: true }))
);
await useTripStore.getState().addPackingItem(1, { name: 'Mat' });
expect(useTripStore.getState().packingItems.map(i => i.id)).toEqual([1, 2, 3]);
await useTripStore.getState().updatePackingItem(1, 1, { name: 'Tarp' });
await useTripStore.getState().togglePackingItem(1, 1, true);
await useTripStore.getState().deletePackingItem(1, 3);
const items = useTripStore.getState().packingItems;
expect(items.map(i => i.id)).toEqual([1, 2]);
expect(items[0].name).toBe('Tarp');
expect(items[0].checked).toBe(1);
expect(items[1].name).toBe('Stove');
expect(items[1].checked).toBe(0);
});
it('FE-STORE-PACKING-015: reorderPackingItems drops unknown ids and keeps unlisted items at the end', async () => {
const a = buildPackingItem({ id: 1, trip_id: 1, sort_order: 0 });
const b = buildPackingItem({ id: 2, trip_id: 1, sort_order: 1 });
const untouched = buildPackingItem({ id: 3, trip_id: 1, sort_order: 2 });
seedStore(useTripStore, { packingItems: [a, b, untouched] });
server.use(
http.put('/api/trips/1/packing/reorder', () => HttpResponse.json({ success: true }))
);
await useTripStore.getState().reorderPackingItems(1, [2, 999, 1]);
const items = useTripStore.getState().packingItems;
expect(items.map(i => i.id)).toEqual([2, 1, 3]);
// sort_order is reindexed against the requested positions, so the slot the
// unknown id occupied leaves a gap until the server's order comes back.
expect(items.map(i => i.sort_order)).toEqual([0, 2, 2]);
});
it('FE-STORE-PACKING-013: togglePackingItem rolls the checkbox back and notifies on failure', async () => {
const item = buildPackingItem({ id: 1, trip_id: 1, checked: 0 });
seedStore(useTripStore, { packingItems: [item] });
server.use(
http.put('/api/trips/1/packing/1', () =>
HttpResponse.json({ error: 'Write failed' }, { status: 500 })
)
);
await useTripStore.getState().togglePackingItem(1, 1, true);
expect(useTripStore.getState().packingItems[0].checked).toBe(0);
expect(addToast).toHaveBeenCalledWith('Write failed', 'error', undefined);
});
});
+287
View File
@@ -0,0 +1,287 @@
// FE-TSLICE-PLACE-001 to FE-TSLICE-PLACE-015 (image upload, ratings, bulk ops, error paths)
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildAssignment, buildPlace } from '../../../tests/helpers/factories';
import { placesApi } from '../../api/client';
import { useTripStore } from '../tripStore';
import type { Place } from '../../types';
beforeEach(() => {
resetAllStores();
server.resetHandlers();
});
afterEach(() => {
vi.restoreAllMocks();
});
/** Rejection shaped like an axios error so getApiErrorMessage picks the server text. */
function apiError(message: string): unknown {
return { response: { data: { error: message } } };
}
describe('placesSlice', () => {
describe('uploadPlaceImage', () => {
it('FE-TSLICE-PLACE-001: applies the returned place and keeps the assignment times', async () => {
const place = buildPlace({ id: 10, trip_id: 1, image_url: null });
const assignment = buildAssignment({
id: 100,
day_id: 3,
place: { ...place, place_time: '09:00', end_time: '10:30' },
});
seedStore(useTripStore, { places: [place], assignments: { '3': [assignment] } });
const uploaded: Place = { ...place, image_url: '/uploads/places/pic.jpg' };
vi.spyOn(placesApi, 'uploadImage').mockResolvedValue({ place: uploaded });
const result = await useTripStore
.getState()
.uploadPlaceImage(1, 10, new File(['x'], 'pic.jpg', { type: 'image/jpeg' }));
expect(result.image_url).toBe('/uploads/places/pic.jpg');
expect(useTripStore.getState().places[0].image_url).toBe('/uploads/places/pic.jpg');
const embedded = useTripStore.getState().assignments['3'][0].place;
expect(embedded.image_url).toBe('/uploads/places/pic.jpg');
// The assignment owns its own times — the fresh place must not overwrite them.
expect(embedded.place_time).toBe('09:00');
expect(embedded.end_time).toBe('10:30');
});
it('FE-TSLICE-PLACE-002: leaves the assignments map alone when no day embeds the place', async () => {
const place = buildPlace({ id: 10, trip_id: 1 });
const other = buildPlace({ id: 20, trip_id: 1 });
const assignment = buildAssignment({ id: 100, day_id: 3, place: other });
seedStore(useTripStore, { places: [place, other], assignments: { '3': [assignment] } });
const before = useTripStore.getState().assignments;
vi.spyOn(placesApi, 'uploadImage').mockResolvedValue({
place: { ...place, image_url: '/uploads/places/pic.jpg' },
});
await useTripStore.getState().uploadPlaceImage(1, 10, new File(['x'], 'pic.jpg'));
expect(useTripStore.getState().assignments).toBe(before);
expect(useTripStore.getState().places[0].image_url).toBe('/uploads/places/pic.jpg');
});
it('FE-TSLICE-PLACE-003: surfaces the server message on failure', async () => {
seedStore(useTripStore, { places: [buildPlace({ id: 10, trip_id: 1 })] });
vi.spyOn(placesApi, 'uploadImage').mockRejectedValue(apiError('Image too large'));
await expect(
useTripStore.getState().uploadPlaceImage(1, 10, new File(['x'], 'pic.jpg')),
).rejects.toThrow('Image too large');
expect(useTripStore.getState().places[0].image_url).toBeNull();
});
});
describe('ratePlace', () => {
it('FE-TSLICE-PLACE-004: a numeric rating is PUT and the fresh average is applied', async () => {
const place = buildPlace({ id: 10, trip_id: 1 });
seedStore(useTripStore, { places: [place] });
let sent: number | undefined;
server.use(
http.put('/api/trips/1/places/10/rating', async ({ request }) => {
const body = await request.json() as { rating: number };
sent = body.rating;
return HttpResponse.json({ place: { ...place, rating_avg: 4.5, rating_count: 2 } });
}),
);
const result = await useTripStore.getState().ratePlace(1, 10, 5);
expect(sent).toBe(5);
expect(result.rating_avg).toBe(4.5);
expect(useTripStore.getState().places[0].rating_count).toBe(2);
});
it('FE-TSLICE-PLACE-005: a null rating clears the vote via DELETE', async () => {
const place = buildPlace({ id: 10, trip_id: 1, rating_avg: 4 });
seedStore(useTripStore, { places: [place] });
let deleted = false;
server.use(
http.delete('/api/trips/1/places/10/rating', () => {
deleted = true;
return HttpResponse.json({ place: { ...place, rating_avg: null, rating_count: 0 } });
}),
);
await useTripStore.getState().ratePlace(1, 10, null);
expect(deleted).toBe(true);
expect(useTripStore.getState().places[0].rating_avg).toBeNull();
});
it('FE-TSLICE-PLACE-006: throws with the server message when rating fails', async () => {
seedStore(useTripStore, { places: [buildPlace({ id: 10, trip_id: 1 })] });
server.use(
http.put('/api/trips/1/places/10/rating', () =>
HttpResponse.json({ error: 'Rating out of range' }, { status: 422 }),
),
);
await expect(useTripStore.getState().ratePlace(1, 10, 9)).rejects.toThrow('Rating out of range');
});
});
describe('deletePlace', () => {
it('FE-TSLICE-PLACE-007: rethrows the server message and keeps the pool intact', async () => {
const place = buildPlace({ id: 10, trip_id: 1 });
seedStore(useTripStore, { places: [place] });
server.use(
http.delete('/api/trips/1/places/10', () =>
HttpResponse.json({ error: 'Place is locked' }, { status: 409 }),
),
);
await expect(useTripStore.getState().deletePlace(1, 10)).rejects.toThrow('Place is locked');
expect(useTripStore.getState().places).toHaveLength(1);
});
});
describe('deletePlacesMany', () => {
it('FE-TSLICE-PLACE-008: removes every listed place and prunes their assignments', async () => {
const a = buildPlace({ id: 10, trip_id: 1 });
const b = buildPlace({ id: 20, trip_id: 1 });
const keep = buildPlace({ id: 30, trip_id: 1 });
seedStore(useTripStore, {
places: [a, b, keep],
assignments: {
'1': [buildAssignment({ id: 100, day_id: 1, place: a }), buildAssignment({ id: 101, day_id: 1, place: keep })],
'2': [buildAssignment({ id: 200, day_id: 2, place: keep })],
},
});
let sentIds: number[] = [];
server.use(
http.post('/api/trips/1/places/bulk-delete', async ({ request }) => {
const body = await request.json() as { ids: number[] };
sentIds = body.ids;
return HttpResponse.json({ deleted: body.ids, count: body.ids.length });
}),
);
await useTripStore.getState().deletePlacesMany(1, [10, 20]);
expect(sentIds).toEqual([10, 20]);
expect(useTripStore.getState().places.map(p => p.id)).toEqual([30]);
expect(useTripStore.getState().assignments['1'].map(x => x.id)).toEqual([101]);
// Day 2 held no deleted place, so it is untouched.
expect(useTripStore.getState().assignments['2']).toHaveLength(1);
});
it('FE-TSLICE-PLACE-009: an empty id list is a no-op and issues no request', async () => {
const a = buildPlace({ id: 10, trip_id: 1 });
seedStore(useTripStore, { places: [a] });
let called = false;
server.use(
http.post('/api/trips/1/places/bulk-delete', () => {
called = true;
return HttpResponse.json({ deleted: [], count: 0 });
}),
);
await useTripStore.getState().deletePlacesMany(1, []);
expect(called).toBe(false);
expect(useTripStore.getState().places).toHaveLength(1);
});
it('FE-TSLICE-PLACE-010: throws and keeps the pool when the bulk delete fails', async () => {
const a = buildPlace({ id: 10, trip_id: 1 });
seedStore(useTripStore, { places: [a] });
server.use(
http.post('/api/trips/1/places/bulk-delete', () =>
HttpResponse.json({ error: 'Bulk delete refused' }, { status: 500 }),
),
);
await expect(useTripStore.getState().deletePlacesMany(1, [10])).rejects.toThrow('Bulk delete refused');
expect(useTripStore.getState().places).toHaveLength(1);
});
});
describe('updatePlacesMany', () => {
it('FE-TSLICE-PLACE-011: leaves the days it does not touch alone', async () => {
const a = buildPlace({ id: 10, trip_id: 1, category_id: 1 });
const other = buildPlace({ id: 20, trip_id: 1, category_id: 1 });
seedStore(useTripStore, {
places: [a, other],
assignments: { '9': [buildAssignment({ id: 900, day_id: 9, place: other })] },
});
const before = useTripStore.getState().assignments;
server.use(
http.post('/api/trips/1/places/bulk-update', () => HttpResponse.json({ updated: [10], count: 1 })),
);
await useTripStore.getState().updatePlacesMany(1, [10], { category_id: 7 });
expect(useTripStore.getState().places.find(p => p.id === 10)?.category_id).toBe(7);
expect(useTripStore.getState().assignments).toBe(before);
});
it('FE-TSLICE-PLACE-012: throws with the server message when the bulk update fails', async () => {
const a = buildPlace({ id: 10, trip_id: 1, category_id: 1 });
seedStore(useTripStore, { places: [a] });
server.use(
http.post('/api/trips/1/places/bulk-update', () =>
HttpResponse.json({ error: 'Unknown category' }, { status: 400 }),
),
);
await expect(
useTripStore.getState().updatePlacesMany(1, [10], { category_id: 99 }),
).rejects.toThrow('Unknown category');
expect(useTripStore.getState().places[0].category_id).toBe(1);
});
});
describe('refreshPlaces', () => {
it('FE-TSLICE-PLACE-013: swallows a failing list request and keeps the current pool', async () => {
const stale = buildPlace({ id: 10, trip_id: 1, name: 'Stale' });
seedStore(useTripStore, { places: [stale] });
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
server.use(
http.get('/api/trips/1/places', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
);
await expect(useTripStore.getState().refreshPlaces(1)).resolves.toBeUndefined();
expect(useTripStore.getState().places[0].name).toBe('Stale');
expect(consoleError).toHaveBeenCalled();
});
});
describe('updatePlace', () => {
it('FE-TSLICE-PLACE-015: throws the server message and leaves the pool untouched', async () => {
const place = buildPlace({ id: 10, trip_id: 1, name: 'Louvre' });
seedStore(useTripStore, { places: [place] });
server.use(
http.put('/api/trips/1/places/10', () =>
HttpResponse.json({ error: 'Place is locked' }, { status: 409 }),
),
);
await expect(
useTripStore.getState().updatePlace(1, 10, { name: 'Orsay' }),
).rejects.toThrow('Place is locked');
expect(useTripStore.getState().places[0].name).toBe('Louvre');
});
});
describe('addPlace', () => {
it('FE-TSLICE-PLACE-014: surfaces the server message on failure', async () => {
server.use(
http.post('/api/trips/1/places', () =>
HttpResponse.json({ error: 'Name required' }, { status: 422 }),
),
);
await expect(useTripStore.getState().addPlace(1, { name: '' })).rejects.toThrow('Name required');
});
});
});
+88 -1
View File
@@ -1,13 +1,21 @@
// FE-STORE-TODO-001 to FE-STORE-TODO-002 (reorder, #969)
// FE-STORE-TODO-001 to FE-STORE-TODO-006 (reorder, #969, plus mutation and error paths)
import { http, HttpResponse } from 'msw';
import { server } from '../../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../../tests/helpers/store';
import { buildTodoItem } from '../../../tests/helpers/factories';
import { useTripStore } from '../tripStore';
let addToast: ReturnType<typeof vi.fn>;
beforeEach(() => {
resetAllStores();
server.resetHandlers();
addToast = vi.fn();
window.__addToast = addToast as unknown as typeof window.__addToast;
});
afterEach(() => {
delete window.__addToast;
});
describe('todoSlice', () => {
@@ -44,5 +52,84 @@ describe('todoSlice', () => {
const items = useTripStore.getState().todoItems;
expect(items[0].id).toBe(1);
expect(items[1].id).toBe(2);
expect(addToast).toHaveBeenCalledWith(expect.any(String), 'error', undefined);
});
it('FE-STORE-TODO-003: updateTodoItem throws the server message and keeps the item', async () => {
const item = buildTodoItem({ id: 1, trip_id: 1, name: 'Book ferry' });
seedStore(useTripStore, { todoItems: [item] });
server.use(
http.put('/api/trips/1/todo/1', () =>
HttpResponse.json({ error: 'Todo is locked' }, { status: 403 })
)
);
await expect(
useTripStore.getState().updateTodoItem(1, 1, { name: 'Book train' })
).rejects.toThrow('Todo is locked');
expect(useTripStore.getState().todoItems[0].name).toBe('Book ferry');
});
it('FE-STORE-TODO-005: add, update, toggle and delete only touch the targeted todo', async () => {
const target = buildTodoItem({ id: 1, trip_id: 1, name: 'Book ferry', checked: 0 });
const sibling = buildTodoItem({ id: 2, trip_id: 1, name: 'Renew passport', checked: 0 });
seedStore(useTripStore, { todoItems: [target, sibling] });
server.use(
http.post('/api/trips/1/todo', () =>
HttpResponse.json({ item: buildTodoItem({ id: 3, trip_id: 1, name: 'Pack meds' }) })
),
http.put('/api/trips/1/todo/1', () =>
HttpResponse.json({ item: { ...target, name: 'Book train', checked: 1 } })
),
http.delete('/api/trips/1/todo/3', () => HttpResponse.json({ success: true }))
);
await useTripStore.getState().addTodoItem(1, { name: 'Pack meds' });
expect(useTripStore.getState().todoItems.map(i => i.id)).toEqual([1, 2, 3]);
await useTripStore.getState().updateTodoItem(1, 1, { name: 'Book train' });
await useTripStore.getState().toggleTodoItem(1, 1, true);
await useTripStore.getState().deleteTodoItem(1, 3);
const items = useTripStore.getState().todoItems;
expect(items.map(i => i.id)).toEqual([1, 2]);
expect(items[0].name).toBe('Book train');
expect(items[0].checked).toBe(1);
expect(items[1].name).toBe('Renew passport');
expect(items[1].checked).toBe(0);
});
it('FE-STORE-TODO-006: reorderTodoItems drops unknown ids and keeps unlisted todos at the end', async () => {
const a = buildTodoItem({ id: 1, trip_id: 1, sort_order: 0 });
const b = buildTodoItem({ id: 2, trip_id: 1, sort_order: 1 });
const untouched = buildTodoItem({ id: 3, trip_id: 1, sort_order: 2 });
seedStore(useTripStore, { todoItems: [a, b, untouched] });
server.use(
http.put('/api/trips/1/todo/reorder', () => HttpResponse.json({ success: true }))
);
await useTripStore.getState().reorderTodoItems(1, [2, 999, 1]);
const items = useTripStore.getState().todoItems;
expect(items.map(i => i.id)).toEqual([2, 1, 3]);
// sort_order is reindexed against the requested positions, so the slot the
// unknown id occupied leaves a gap until the server's order comes back.
expect(items.map(i => i.sort_order)).toEqual([0, 2, 2]);
});
it('FE-STORE-TODO-004: toggleTodoItem rolls the checkbox back and notifies on failure', async () => {
const item = buildTodoItem({ id: 1, trip_id: 1, checked: 0 });
seedStore(useTripStore, { todoItems: [item] });
server.use(
http.put('/api/trips/1/todo/1', () =>
HttpResponse.json({ error: 'Write failed' }, { status: 500 })
)
);
await useTripStore.getState().toggleTodoItem(1, 1, true);
expect(useTripStore.getState().todoItems[0].checked).toBe(0);
expect(addToast).toHaveBeenCalledWith('Write failed', 'error', undefined);
});
});
+479
View File
@@ -0,0 +1,479 @@
// FE-TSTORE-001 to FE-TSTORE-021 (trip-scoped root store: load, hydrate, refresh, mutate)
import { http, HttpResponse } from 'msw';
import { server } from '../../tests/helpers/msw/server';
import { resetAllStores, seedStore } from '../../tests/helpers/store';
import {
buildAssignment,
buildBudgetItem,
buildCategory,
buildDay,
buildDayNote,
buildPackingItem,
buildPlace,
buildReservation,
buildTag,
buildTodoItem,
buildTrip,
buildTripFile,
} from '../../tests/helpers/factories';
import { offlineDb } from '../db/offlineDb';
import { setForcedOffline } from '../sync/networkMode';
import { useTripStore } from './tripStore';
/** Every cache table loadTrip reads from, so one test can never see another's writes. */
async function clearCache(): Promise<void> {
await Promise.all([
offlineDb.trips.clear(),
offlineDb.days.clear(),
offlineDb.places.clear(),
offlineDb.packingItems.clear(),
offlineDb.todoItems.clear(),
offlineDb.budgetItems.clear(),
offlineDb.reservations.clear(),
offlineDb.tripFiles.clear(),
offlineDb.tags.clear(),
offlineDb.categories.clear(),
]);
}
beforeEach(async () => {
resetAllStores();
server.resetHandlers();
await clearCache();
});
afterEach(() => {
setForcedOffline(false);
vi.restoreAllMocks();
});
/** Days as the day list endpoint returns them: with embedded assignments + notes. */
function serverDays() {
const place = buildPlace({ id: 500, trip_id: 1 });
return [
buildDay({
id: 1,
trip_id: 1,
day_number: 1,
assignments: [buildAssignment({ id: 900, day_id: 1, place })],
notes_items: [buildDayNote({ id: 800, day_id: 1, text: 'Pick up keys' })],
}),
// A day row that arrives without the embedded arrays at all.
buildDay({ id: 2, trip_id: 1, day_number: 2, assignments: undefined, notes_items: undefined }),
];
}
describe('tripStore', () => {
describe('selectors and filters', () => {
it('FE-TSTORE-001: setSelectedDay, setPlacesFilter and setPlacesCategoryFilter write through', () => {
useTripStore.getState().setSelectedDay(42);
useTripStore.getState().setPlacesFilter('unplanned');
useTripStore.getState().setPlacesCategoryFilter(new Set(['3', '7']));
const state = useTripStore.getState();
expect(state.selectedDayId).toBe(42);
expect(state.placesFilter).toBe('unplanned');
expect([...state.placesCategoryFilter]).toEqual(['3', '7']);
useTripStore.getState().setSelectedDay(null);
expect(useTripStore.getState().selectedDayId).toBeNull();
});
});
describe('resetTrip', () => {
it('FE-TSTORE-002: clears every trip-scoped slice but keeps the global tags and categories', () => {
seedStore(useTripStore, {
trip: buildTrip({ id: 1 }),
days: [buildDay({ id: 1, trip_id: 1 })],
places: [buildPlace({ trip_id: 1 })],
assignments: { '1': [buildAssignment({ day_id: 1 })] },
dayNotes: { '1': [buildDayNote({ day_id: 1 })] },
packingItems: [buildPackingItem({ trip_id: 1 })],
todoItems: [buildTodoItem({ trip_id: 1 })],
budgetItems: [buildBudgetItem({ trip_id: 1 })],
files: [buildTripFile({ trip_id: 1 })],
reservations: [buildReservation({ trip_id: 1 })],
tags: [buildTag({ id: 5 })],
categories: [buildCategory({ id: 6 })],
selectedDayId: 1,
placesFilter: 'unplanned',
placesCategoryFilter: new Set(['3']),
error: 'stale error',
});
useTripStore.getState().resetTrip();
const state = useTripStore.getState();
expect(state.trip).toBeNull();
expect(state.days).toEqual([]);
expect(state.places).toEqual([]);
expect(state.assignments).toEqual({});
expect(state.dayNotes).toEqual({});
expect(state.packingItems).toEqual([]);
expect(state.todoItems).toEqual([]);
expect(state.budgetItems).toEqual([]);
expect(state.files).toEqual([]);
expect(state.reservations).toEqual([]);
expect(state.selectedDayId).toBeNull();
expect(state.placesFilter).toBe('all');
expect(state.placesCategoryFilter.size).toBe(0);
expect(state.error).toBeNull();
// Global lookups survive a trip switch.
expect(state.tags.map(t => t.id)).toEqual([5]);
expect(state.categories.map(c => c.id)).toEqual([6]);
});
});
describe('loadTrip', () => {
it('FE-TSTORE-003: fills every slice and builds the assignments/dayNotes maps', async () => {
server.use(
http.get('/api/trips/1', () => HttpResponse.json({ trip: buildTrip({ id: 1, title: 'Paris' }) })),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: serverDays() })),
http.get('/api/trips/1/places', () => HttpResponse.json({ places: [buildPlace({ id: 500, trip_id: 1 })] })),
http.get('/api/trips/1/packing', () => HttpResponse.json({ items: [buildPackingItem({ id: 60, trip_id: 1 })] })),
http.get('/api/trips/1/todo', () => HttpResponse.json({ items: [buildTodoItem({ id: 70, trip_id: 1 })] })),
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [buildBudgetItem({ id: 80, trip_id: 1 })] })),
http.get('/api/trips/1/reservations', () => HttpResponse.json({ reservations: [buildReservation({ id: 90, trip_id: 1 })] })),
http.get('/api/trips/1/files', () => HttpResponse.json({ files: [buildTripFile({ id: 95, trip_id: 1 })] })),
http.get('/api/tags', () => HttpResponse.json({ tags: [buildTag({ id: 11 })] })),
http.get('/api/categories', () => HttpResponse.json({ categories: [buildCategory({ id: 12 })] })),
);
await useTripStore.getState().loadTrip(1);
const state = useTripStore.getState();
expect(state.trip?.title).toBe('Paris');
expect(state.days.map(d => d.id)).toEqual([1, 2]);
expect(state.places.map(p => p.id)).toEqual([500]);
expect(state.packingItems.map(i => i.id)).toEqual([60]);
expect(state.todoItems.map(i => i.id)).toEqual([70]);
expect(state.budgetItems.map(i => i.id)).toEqual([80]);
expect(state.reservations.map(r => r.id)).toEqual([90]);
expect(state.files.map(f => f.id)).toEqual([95]);
expect(state.tags.map(t => t.id)).toEqual([11]);
expect(state.categories.map(c => c.id)).toEqual([12]);
expect(state.assignments['1'].map(a => a.id)).toEqual([900]);
expect(state.dayNotes['1'].map(n => n.id)).toEqual([800]);
// A day row without the embedded arrays still gets an entry.
expect(state.assignments['2']).toEqual([]);
expect(state.dayNotes['2']).toEqual([]);
expect(state.isLoading).toBe(false);
expect(state.error).toBeNull();
});
it('FE-TSTORE-004: drops the previously loaded trip before fetching the next one', async () => {
seedStore(useTripStore, {
trip: buildTrip({ id: 9, title: 'Old trip' }),
places: [buildPlace({ id: 111, trip_id: 9 })],
});
let placesDuringLoad: number[] = [];
server.use(
http.get('/api/trips/1', () => {
placesDuringLoad = useTripStore.getState().places.map(p => p.id);
return HttpResponse.json({ trip: buildTrip({ id: 1 }) });
}),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: [] })),
http.get('/api/trips/1/places', () => HttpResponse.json({ places: [] })),
);
await useTripStore.getState().loadTrip(1);
expect(placesDuringLoad).toEqual([]);
expect(useTripStore.getState().trip?.id).toBe(1);
});
it('FE-TSTORE-005: a failing budget/reservations/files fetch is non-fatal', async () => {
server.use(
http.get('/api/trips/1/days', () => HttpResponse.json({ days: [] })),
http.get('/api/trips/1/budget', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
http.get('/api/trips/1/reservations', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
http.get('/api/trips/1/files', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
);
await useTripStore.getState().loadTrip(1);
const state = useTripStore.getState();
expect(state.trip?.id).toBe(1);
expect(state.budgetItems).toEqual([]);
expect(state.reservations).toEqual([]);
expect(state.files).toEqual([]);
expect(state.error).toBeNull();
});
it('FE-TSTORE-006: falls back to the cached tags and categories when their endpoints fail', async () => {
await offlineDb.tags.put(buildTag({ id: 31, name: 'Cached tag' }));
await offlineDb.categories.put(buildCategory({ id: 32, name: 'Cached category' }));
server.use(
http.get('/api/trips/1/days', () => HttpResponse.json({ days: [] })),
http.get('/api/tags', () => HttpResponse.json({ error: 'offline' }, { status: 502 })),
http.get('/api/categories', () => HttpResponse.json({ error: 'offline' }, { status: 502 })),
);
await useTripStore.getState().loadTrip(1);
expect(useTripStore.getState().tags.map(t => t.name)).toEqual(['Cached tag']);
expect(useTripStore.getState().categories.map(c => c.name)).toEqual(['Cached category']);
});
it('FE-TSTORE-020: serves the whole trip from the offline cache when the app is forced offline', async () => {
await offlineDb.trips.put(buildTrip({ id: 1, title: 'Cached trip' }));
await offlineDb.days.bulkPut([buildDay({ id: 1, trip_id: 1, day_number: 1 })]);
await offlineDb.places.bulkPut([buildPlace({ id: 502, trip_id: 1 })]);
await offlineDb.packingItems.bulkPut([buildPackingItem({ id: 62, trip_id: 1 })]);
await offlineDb.todoItems.bulkPut([buildTodoItem({ id: 73, trip_id: 1 })]);
await offlineDb.budgetItems.bulkPut([buildBudgetItem({ id: 82, trip_id: 1 })]);
await offlineDb.reservations.bulkPut([buildReservation({ id: 93, trip_id: 1 })]);
await offlineDb.tripFiles.bulkPut([buildTripFile({ id: 97, trip_id: 1 })]);
await offlineDb.tags.put(buildTag({ id: 41, name: 'Offline tag' }));
await offlineDb.categories.put(buildCategory({ id: 42, name: 'Offline category' }));
// Any request reaching the network would mean the offline gate leaked.
const leaked: string[] = [];
server.use(
http.get('/api/*', ({ request }) => {
leaked.push(new URL(request.url).pathname);
return HttpResponse.json({}, { status: 500 });
}),
);
setForcedOffline(true);
await useTripStore.getState().loadTrip(1);
expect(leaked).toEqual([]);
const state = useTripStore.getState();
expect(state.trip?.title).toBe('Cached trip');
expect(state.days.map(d => d.id)).toEqual([1]);
expect(state.places.map(p => p.id)).toEqual([502]);
expect(state.packingItems.map(i => i.id)).toEqual([62]);
expect(state.todoItems.map(i => i.id)).toEqual([73]);
expect(state.budgetItems.map(i => i.id)).toEqual([82]);
expect(state.reservations.map(r => r.id)).toEqual([93]);
expect(state.files.map(f => f.id)).toEqual([97]);
expect(state.tags.map(t => t.name)).toEqual(['Offline tag']);
expect(state.categories.map(c => c.name)).toEqual(['Offline category']);
expect(state.isLoading).toBe(false);
});
it('FE-TSTORE-021: reports a cache miss as an error when forced offline', async () => {
setForcedOffline(true);
await expect(useTripStore.getState().loadTrip(1)).rejects.toThrow();
expect(useTripStore.getState().error).toBe('No cached trip data available offline');
expect(useTripStore.getState().isLoading).toBe(false);
});
it('FE-TSTORE-007: sets the error state and rethrows when the trip itself cannot be fetched', async () => {
server.use(
http.get('/api/trips/1', () => HttpResponse.json({ error: 'Forbidden' }, { status: 403 })),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: [] })),
);
await expect(useTripStore.getState().loadTrip(1)).rejects.toThrow();
const state = useTripStore.getState();
expect(state.isLoading).toBe(false);
expect(state.error).toContain('403');
expect(state.trip).toBeNull();
});
});
describe('hydrateActiveTrip', () => {
it('FE-TSTORE-008: silently re-pulls every collaborative slice and nudges the planner', async () => {
seedStore(useTripStore, { trip: buildTrip({ id: 1 }), places: [], days: [] });
server.use(
http.get('/api/trips/1/days', () => HttpResponse.json({ days: serverDays() })),
http.get('/api/trips/1/places', () => HttpResponse.json({ places: [buildPlace({ id: 501, trip_id: 1 })] })),
http.get('/api/trips/1/packing', () => HttpResponse.json({ items: [buildPackingItem({ id: 61, trip_id: 1 })] })),
http.get('/api/trips/1/todo', () => HttpResponse.json({ items: [buildTodoItem({ id: 71, trip_id: 1 })] })),
http.get('/api/trips/1/budget', () => HttpResponse.json({ items: [buildBudgetItem({ id: 81, trip_id: 1 })] })),
http.get('/api/trips/1/reservations', () => HttpResponse.json({ reservations: [buildReservation({ id: 91, trip_id: 1 })] })),
http.get('/api/trips/1/files', () => HttpResponse.json({ files: [buildTripFile({ id: 96, trip_id: 1 })] })),
);
const nudged = vi.fn();
window.addEventListener('accommodations:refresh', nudged);
await useTripStore.getState().hydrateActiveTrip(1);
window.removeEventListener('accommodations:refresh', nudged);
const state = useTripStore.getState();
expect(state.days.map(d => d.id)).toEqual([1, 2]);
expect(state.places.map(p => p.id)).toEqual([501]);
expect(state.packingItems.map(i => i.id)).toEqual([61]);
expect(state.todoItems.map(i => i.id)).toEqual([71]);
expect(state.budgetItems.map(i => i.id)).toEqual([81]);
expect(state.reservations.map(r => r.id)).toEqual([91]);
expect(state.files.map(f => f.id)).toEqual([96]);
// The trip itself is not re-fetched — no splash, no resetTrip.
expect(state.isLoading).toBe(false);
expect(nudged).toHaveBeenCalledTimes(1);
});
it('FE-TSTORE-009: one failing resource does not wipe the others', async () => {
const stalePlace = buildPlace({ id: 111, trip_id: 1, name: 'Kept' });
seedStore(useTripStore, { places: [stalePlace], packingItems: [], todoItems: [] });
vi.spyOn(console, 'error').mockImplementation(() => {});
server.use(
http.get('/api/trips/1/days', () => HttpResponse.json({ days: [] })),
http.get('/api/trips/1/places', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
http.get('/api/trips/1/packing', () => HttpResponse.json({ error: 'nope' }, { status: 500 })),
http.get('/api/trips/1/todo', () => HttpResponse.json({ items: [buildTodoItem({ id: 72, trip_id: 1 })] })),
);
await expect(useTripStore.getState().hydrateActiveTrip(1)).resolves.toBeUndefined();
expect(useTripStore.getState().places.map(p => p.name)).toEqual(['Kept']);
expect(useTripStore.getState().todoItems.map(i => i.id)).toEqual([72]);
});
});
describe('refreshDays', () => {
it('FE-TSTORE-010: rebuilds the days list plus the assignments and notes maps', async () => {
seedStore(useTripStore, { days: [], assignments: { '99': [] }, dayNotes: { '99': [] } });
server.use(http.get('/api/trips/1/days', () => HttpResponse.json({ days: serverDays() })));
await useTripStore.getState().refreshDays(1);
const state = useTripStore.getState();
expect(state.days.map(d => d.id)).toEqual([1, 2]);
expect(state.assignments['1'].map(a => a.id)).toEqual([900]);
expect(state.dayNotes['1'].map(n => n.id)).toEqual([800]);
// The maps are rebuilt from scratch, so a stale day key is gone.
expect(state.assignments['99']).toBeUndefined();
});
it('FE-TSTORE-011: swallows a failing day list and keeps the current days', async () => {
const day = buildDay({ id: 1, trip_id: 1 });
seedStore(useTripStore, { days: [day] });
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
server.use(
http.get('/api/trips/1/days', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
);
await expect(useTripStore.getState().refreshDays(1)).resolves.toBeUndefined();
expect(useTripStore.getState().days.map(d => d.id)).toEqual([1]);
expect(consoleError).toHaveBeenCalled();
});
});
describe('updateTrip', () => {
it('FE-TSTORE-012: persists the patch, refreshes days and re-pulls the re-anchored bookings', async () => {
seedStore(useTripStore, { trip: buildTrip({ id: 1, title: 'Old' }), days: [], reservations: [] });
let sent: Record<string, unknown> = {};
server.use(
http.put('/api/trips/1', async ({ request }) => {
sent = await request.json() as Record<string, unknown>;
return HttpResponse.json({ trip: buildTrip({ id: 1, title: 'New', start_date: '2025-06-01' }) });
}),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: serverDays() })),
http.get('/api/trips/1/reservations', () =>
HttpResponse.json({ reservations: [buildReservation({ id: 92, trip_id: 1, title: 'Re-anchored' })] }),
),
);
const result = await useTripStore.getState().updateTrip(1, { title: 'New', start_date: '2025-06-01' });
expect(result.title).toBe('New');
expect(sent).toMatchObject({ title: 'New', start_date: '2025-06-01' });
expect(useTripStore.getState().trip?.title).toBe('New');
expect(useTripStore.getState().days.map(d => d.id)).toEqual([1, 2]);
expect(useTripStore.getState().assignments['1']).toHaveLength(1);
expect(useTripStore.getState().reservations.map(r => r.title)).toEqual(['Re-anchored']);
});
it('FE-TSTORE-013: forwards the date_shift_mode flag', async () => {
let sent: Record<string, unknown> = {};
server.use(
http.put('/api/trips/1', async ({ request }) => {
sent = await request.json() as Record<string, unknown>;
return HttpResponse.json({ trip: buildTrip({ id: 1 }) });
}),
http.get('/api/trips/1/days', () => HttpResponse.json({ days: [] })),
);
await useTripStore.getState().updateTrip(1, { start_date: '2025-07-01', date_shift_mode: 'shift_all' });
expect(sent.date_shift_mode).toBe('shift_all');
});
it('FE-TSTORE-014: throws the server message and leaves the trip untouched', async () => {
const trip = buildTrip({ id: 1, title: 'Old' });
seedStore(useTripStore, { trip });
server.use(
http.put('/api/trips/1', () => HttpResponse.json({ error: 'Not the owner' }, { status: 403 })),
);
await expect(useTripStore.getState().updateTrip(1, { title: 'New' })).rejects.toThrow('Not the owner');
expect(useTripStore.getState().trip?.title).toBe('Old');
});
});
describe('addTag', () => {
it('FE-TSTORE-015: appends the created tag to the global list', async () => {
seedStore(useTripStore, { tags: [buildTag({ id: 1, name: 'Existing' })] });
server.use(
http.post('/api/tags', () => HttpResponse.json({ tag: buildTag({ id: 2, name: 'Food', color: '#00ff00' }) })),
);
const created = await useTripStore.getState().addTag({ name: 'Food', color: '#00ff00' });
expect(created.id).toBe(2);
expect(useTripStore.getState().tags.map(t => t.name)).toEqual(['Existing', 'Food']);
});
it('FE-TSTORE-016: throws the server message and keeps the list unchanged', async () => {
seedStore(useTripStore, { tags: [buildTag({ id: 1 })] });
server.use(
http.post('/api/tags', () => HttpResponse.json({ error: 'Tag exists' }, { status: 409 })),
);
await expect(useTripStore.getState().addTag({ name: 'Food' })).rejects.toThrow('Tag exists');
expect(useTripStore.getState().tags).toHaveLength(1);
});
});
describe('addCategory', () => {
it('FE-TSTORE-017: appends the created category to the global list', async () => {
seedStore(useTripStore, { categories: [buildCategory({ id: 1, name: 'Existing' })] });
server.use(
http.post('/api/categories', () =>
HttpResponse.json({ category: buildCategory({ id: 2, name: 'Museums', icon: 'landmark' }) }),
),
);
const created = await useTripStore.getState().addCategory({ name: 'Museums', icon: 'landmark' });
expect(created.icon).toBe('landmark');
expect(useTripStore.getState().categories.map(c => c.name)).toEqual(['Existing', 'Museums']);
});
it('FE-TSTORE-018: throws the server message and keeps the list unchanged', async () => {
seedStore(useTripStore, { categories: [buildCategory({ id: 1 })] });
server.use(
http.post('/api/categories', () => HttpResponse.json({ error: 'Category exists' }, { status: 409 })),
);
await expect(useTripStore.getState().addCategory({ name: 'Museums' })).rejects.toThrow('Category exists');
expect(useTripStore.getState().categories).toHaveLength(1);
});
});
describe('handleRemoteEvent', () => {
it('FE-TSTORE-019: routes a socket event into the store', () => {
const place = buildPlace({ id: 500, trip_id: 1, name: 'Before' });
seedStore(useTripStore, { places: [place] });
useTripStore.getState().handleRemoteEvent({
type: 'place:updated',
place: { ...place, name: 'After' },
});
expect(useTripStore.getState().places[0].name).toBe('After');
});
});
});
+368
View File
@@ -0,0 +1,368 @@
// FE-STORE-VCY-001 to FE-STORE-VCY-018
// Complements tests/unit/stores/vacayStore.test.ts: optimistic toggles and their
// rollbacks, the leave-year window plumbing and the holiday-marker merge rules.
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { http, HttpResponse } from 'msw';
import { server } from '../../tests/helpers/msw/server';
import { resetAllStores } from '../../tests/helpers/store';
import { useVacayStore } from './vacayStore';
import { useAuthStore } from './authStore';
import type { HolidayInfo, VacayEntry, VacayPlan, VacayYearSettings } from '../types';
const FISCAL_JULY: VacayYearSettings = {
year_type: 'fiscal', year_start_month: 7, year_start_day: 1, hire_date: null,
};
function buildPlan(over: Partial<VacayPlan> = {}): VacayPlan {
return {
id: 1,
holidays_enabled: true,
school_holidays_enabled: false,
holidays_region: null,
holiday_calendars: [],
block_weekends: true,
carry_over_enabled: false,
company_holidays_enabled: false,
...over,
};
}
function markersOn(date: string): HolidayInfo[] {
const value = useVacayStore.getState().holidays[date];
if (!value) return [];
return Array.isArray(value) ? value : [value];
}
beforeEach(() => {
resetAllStores();
useAuthStore.setState({ user: { id: 1, username: 'alice', email: 'a@t.app', role: 'user' } as never });
});
describe('vacayStore optimistic updates', () => {
it('FE-STORE-VCY-001: toggling an empty day adds an entry with the person color', async () => {
let resolveToggle = (): void => {};
const gate = new Promise<void>(res => { resolveToggle = res; });
server.use(http.post('/api/addons/vacay/entries/toggle', async () => {
await gate;
return HttpResponse.json({ success: true });
}));
useVacayStore.setState({
selectedYear: 2025,
users: [{ id: 1, username: 'alice', color: '#3b82f6' }],
entries: [],
});
const pending = useVacayStore.getState().toggleEntry('2025-06-20');
// The cell reacts before the round trip finishes.
expect(useVacayStore.getState().entries).toEqual([
{ date: '2025-06-20', user_id: 1, fraction: 1, kind: 'vacation', person_color: '#3b82f6', person_name: 'alice' },
]);
resolveToggle();
await pending;
// Reconciled from the server afterwards.
expect(useVacayStore.getState().entries).toHaveLength(2);
});
it('FE-STORE-VCY-002: toggling the same fraction and kind again clears the day', async () => {
const entries: VacayEntry[] = [
{ date: '2025-06-20', user_id: 1, fraction: 1, kind: 'vacation' },
{ date: '2025-06-21', user_id: 1 },
];
useVacayStore.setState({ selectedYear: 2025, entries });
let seen: VacayEntry[] = [];
server.use(http.post('/api/addons/vacay/entries/toggle', () => {
seen = useVacayStore.getState().entries;
return HttpResponse.json({ success: true });
}));
await useVacayStore.getState().toggleEntry('2025-06-20', 1, 1, 'vacation');
expect(seen.map(e => e.date)).toEqual(['2025-06-21']);
});
it('FE-STORE-VCY-003: a legacy entry without fraction or kind counts as a full vacation day', async () => {
useVacayStore.setState({ selectedYear: 2025, entries: [{ date: '2025-06-20', user_id: 1 }] });
let seen: VacayEntry[] = [];
server.use(http.post('/api/addons/vacay/entries/toggle', () => {
seen = useVacayStore.getState().entries;
return HttpResponse.json({ success: true });
}));
await useVacayStore.getState().toggleEntry('2025-06-20', 1, 1, 'vacation');
expect(seen).toEqual([]);
});
it('FE-STORE-VCY-004: a different fraction or kind converts the day instead of clearing it', async () => {
useVacayStore.setState({
selectedYear: 2025,
entries: [{ date: '2025-06-20', user_id: 1, fraction: 1, kind: 'vacation' }],
});
let seen: VacayEntry[] = [];
server.use(http.post('/api/addons/vacay/entries/toggle', () => {
seen = useVacayStore.getState().entries;
return HttpResponse.json({ success: true });
}));
await useVacayStore.getState().toggleEntry('2025-06-20', 1, 0.5, 'comp');
expect(seen).toEqual([{ date: '2025-06-20', user_id: 1, fraction: 0.5, kind: 'comp' }]);
});
it('FE-STORE-VCY-005: a rejected toggle restores the previous entries and rethrows', async () => {
const entries: VacayEntry[] = [{ date: '2025-06-20', user_id: 1 }];
const stats = [{
user_id: 1, person_name: 'alice', person_color: '#3b82f6', year: 2025,
vacation_days: 30, carried_over: 0, total_available: 30, used: 1, remaining: 29,
}];
useVacayStore.setState({ selectedYear: 2025, entries, stats });
server.use(http.post('/api/addons/vacay/entries/toggle', () =>
HttpResponse.json({ error: 'locked' }, { status: 403 })));
await expect(useVacayStore.getState().toggleEntry('2025-06-21', 1)).rejects.toThrow();
expect(useVacayStore.getState().entries).toEqual(entries);
expect(useVacayStore.getState().stats).toEqual(stats);
});
it('FE-STORE-VCY-006: toggling for an unknown person still records the entry', async () => {
useVacayStore.setState({ selectedYear: 2025, users: [], entries: [] });
let seen: VacayEntry[] = [];
server.use(http.post('/api/addons/vacay/entries/toggle', () => {
seen = useVacayStore.getState().entries;
return HttpResponse.json({ success: true });
}));
await useVacayStore.getState().toggleEntry('2025-06-20', 4);
expect(seen).toEqual([
{ date: '2025-06-20', user_id: 4, fraction: 1, kind: 'vacation', person_color: undefined, person_name: undefined },
]);
});
it('FE-STORE-VCY-007: company-holiday toggles add and remove the day optimistically', async () => {
useVacayStore.setState({ selectedYear: 2025, companyHolidays: [{ date: '2025-12-24' }] });
const seen: { date: string; note?: string }[][] = [];
server.use(http.post('/api/addons/vacay/entries/company-holiday', () => {
seen.push(useVacayStore.getState().companyHolidays);
return HttpResponse.json({ success: true });
}));
await useVacayStore.getState().toggleCompanyHoliday('2025-12-24');
await useVacayStore.getState().toggleCompanyHoliday('2025-12-25');
expect(seen[0]).toEqual([]);
expect(seen[1]).toEqual([{ date: '2025-12-25' }]);
});
it('FE-STORE-VCY-008: a rejected company-holiday toggle rolls the day back', async () => {
const companyHolidays = [{ date: '2025-12-24' }];
useVacayStore.setState({ selectedYear: 2025, companyHolidays });
server.use(http.post('/api/addons/vacay/entries/company-holiday', () =>
HttpResponse.json({ error: 'nope' }, { status: 500 })));
await expect(useVacayStore.getState().toggleCompanyHoliday('2025-12-25')).rejects.toThrow();
expect(useVacayStore.getState().companyHolidays).toEqual(companyHolidays);
});
});
describe('vacayStore leave-year window', () => {
it('FE-STORE-VCY-009: an empty year list falls back to the current period', async () => {
useVacayStore.setState({ yearSettings: FISCAL_JULY });
server.use(http.get('/api/addons/vacay/years', () => HttpResponse.json({ years: [] })));
await useVacayStore.getState().loadYears();
const now = new Date();
const expected = now.getMonth() >= 6 ? now.getFullYear() : now.getFullYear() - 1;
expect(useVacayStore.getState().years).toEqual([]);
expect(useVacayStore.getState().selectedYear).toBe(expected);
});
it('FE-STORE-VCY-010: updating the year settings reloads everything the window feeds', async () => {
useVacayStore.setState({ selectedYear: 2026, plan: buildPlan({ holidays_enabled: false }) });
const hits: string[] = [];
server.use(
http.get('/api/addons/vacay/entries/:year', ({ params }) => {
hits.push(`entries:${params.year as string}`);
return HttpResponse.json({ entries: [], companyHolidays: [] });
}),
http.get('/api/addons/vacay/stats/:year', ({ params }) => {
hits.push(`stats:${params.year as string}`);
return HttpResponse.json({ stats: [] });
}),
http.get('/api/addons/vacay/shares/calendars/:year', ({ params }) => {
hits.push(`shared:${params.year as string}`);
return HttpResponse.json({ calendars: [] });
}),
);
await useVacayStore.getState().updateYearSettings({
year_type: 'fiscal', year_start_month: 7, year_start_day: 1, hire_date: null,
});
expect(useVacayStore.getState().yearSettings.year_type).toBe('fiscal');
expect(useVacayStore.getState().yearSettings.year_start_month).toBe(7);
expect(hits).toEqual(['entries:2026', 'stats:2026', 'shared:2026']);
});
it('FE-STORE-VCY-011: a settings response without a body falls back to the calendar year', async () => {
useVacayStore.setState({ yearSettings: FISCAL_JULY });
server.use(http.put('/api/addons/vacay/year-settings', () => HttpResponse.json({})));
await useVacayStore.getState().updateYearSettings({
year_type: 'calendar', year_start_month: 1, year_start_day: 1, hire_date: null,
});
expect(useVacayStore.getState().yearSettings).toEqual({
year_type: 'calendar', year_start_month: 1, year_start_day: 1, hire_date: null,
});
});
});
describe('vacayStore holiday markers', () => {
it('FE-STORE-VCY-012: two calendars on the same day keep both markers', async () => {
useVacayStore.setState({
selectedYear: 2026,
plan: buildPlan({
holiday_calendars: [
{ id: 1, plan_id: 1, region: 'DE', label: 'DE', color: '#fecaca', sort_order: 0 },
{ id: 2, plan_id: 1, region: 'FR', label: 'FR', color: '#bbf7d0', sort_order: 1 },
],
}),
});
server.use(http.get('/api/addons/vacay/holidays/:year/:country', () => HttpResponse.json([
{ date: '2026-12-25', name: 'Christmas', localName: 'Weihnachten', global: true, counties: null },
])));
await useVacayStore.getState().loadHolidays(2026);
expect(markersOn('2026-12-25').map(m => m.color)).toEqual(['#fecaca', '#bbf7d0']);
});
it('FE-STORE-VCY-013: a shifted year loads both calendar years without duplicating a marker', async () => {
useVacayStore.setState({
selectedYear: 2026,
yearSettings: FISCAL_JULY,
plan: buildPlan({
holiday_calendars: [{ id: 1, plan_id: 1, region: 'DE', label: 'DE', color: '#fecaca', sort_order: 0 }],
}),
});
const requested: string[] = [];
server.use(http.get('/api/addons/vacay/holidays/:year/:country', ({ params }) => {
requested.push(params.year as string);
return HttpResponse.json([
{ date: '2026-12-25', name: 'Christmas', localName: 'Weihnachten', global: true, counties: null },
// Outside the Jul 2026 – Jun 2027 window, so it never reaches the map.
{ date: '2026-05-01', name: 'Labour Day', localName: 'Tag der Arbeit', global: true, counties: null },
]);
}));
await useVacayStore.getState().loadHolidays(2026);
expect(requested).toEqual(['2026', '2027']);
expect(markersOn('2026-12-25')).toHaveLength(1);
expect(markersOn('2026-05-01')).toHaveLength(0);
});
it('FE-STORE-VCY-014: a country-level calendar is skipped when the data is region-split', async () => {
useVacayStore.setState({
selectedYear: 2026,
plan: buildPlan({
holiday_calendars: [{ id: 1, plan_id: 1, region: 'DE', label: 'DE', color: '#fecaca', sort_order: 0 }],
}),
});
server.use(http.get('/api/addons/vacay/holidays/:year/:country', () => HttpResponse.json([
{ date: '2026-11-01', name: 'All Saints', localName: 'Allerheiligen', global: false, counties: ['DE-BY'] },
])));
await useVacayStore.getState().loadHolidays(2026);
expect(useVacayStore.getState().holidays).toEqual({});
});
it('FE-STORE-VCY-015: school-holiday ranges expand into days and accept a plain name', async () => {
useVacayStore.setState({
selectedYear: 2026,
plan: buildPlan({
holidays_enabled: false,
school_holidays_enabled: true,
holiday_calendars: [{ id: 1, plan_id: 1, region: 'NL', label: 'NL', color: '#bbf7d0', sort_order: 0, type: 'school_holiday' }],
}),
});
server.use(http.get('/api/addons/vacay/school-holidays/:year/:country', () => HttpResponse.json([
{ startDate: '2026-05-01', endDate: '2026-05-03', name: 'Meivakantie' },
// No start date at all, and a range the date parser cannot read.
{ endDate: '2026-06-10', name: 'Broken' },
{ startDate: 'not-a-date', endDate: 'nope', name: 'Unparseable' },
])));
await useVacayStore.getState().loadHolidays(2026);
const holidays = useVacayStore.getState().holidays;
expect(Object.keys(holidays).sort()).toEqual(['2026-05-01', '2026-05-02', '2026-05-03']);
expect(markersOn('2026-05-02')[0].name).toBe('Meivakantie');
});
it('FE-STORE-VCY-016: an unnamed school holiday gets the generic label', async () => {
useVacayStore.setState({
selectedYear: 2026,
plan: buildPlan({
holidays_enabled: false,
school_holidays_enabled: true,
holiday_calendars: [{ id: 1, plan_id: 1, region: 'NL', label: null, color: '#bbf7d0', sort_order: 0, type: 'school_holiday' }],
}),
});
server.use(http.get('/api/addons/vacay/school-holidays/:year/:country', () => HttpResponse.json([
{ startDate: '2026-05-01', name: [] },
])));
await useVacayStore.getState().loadHolidays(2026);
expect(markersOn('2026-05-01')[0].name).toBe('School holidays');
});
it('FE-STORE-VCY-017: a failing holiday request leaves the other calendars intact', async () => {
useVacayStore.setState({
selectedYear: 2026,
plan: buildPlan({
holiday_calendars: [
{ id: 1, plan_id: 1, region: 'DE', label: 'DE', color: '#fecaca', sort_order: 0 },
{ id: 2, plan_id: 1, region: 'FR', label: 'FR', color: '#bbf7d0', sort_order: 1 },
],
}),
});
server.use(http.get('/api/addons/vacay/holidays/:year/:country', ({ params }) => {
if (params.country === 'DE') return HttpResponse.json({ error: 'down' }, { status: 500 });
return HttpResponse.json([
{ date: '2026-07-14', name: 'Bastille Day', localName: 'Fête nationale', global: true, counties: null },
]);
}));
await useVacayStore.getState().loadHolidays(2026);
expect(markersOn('2026-07-14').map(m => m.color)).toEqual(['#bbf7d0']);
});
it('FE-STORE-VCY-018: disabled calendar types are not fetched at all', async () => {
const fetched = vi.fn(() => undefined);
useVacayStore.setState({
selectedYear: 2026,
plan: buildPlan({
holidays_enabled: false,
school_holidays_enabled: false,
holiday_calendars: [
{ id: 1, plan_id: 1, region: 'DE', label: 'DE', color: '#fecaca', sort_order: 0 },
{ id: 2, plan_id: 1, region: 'NL', label: 'NL', color: '#bbf7d0', sort_order: 1, type: 'school_holiday' },
],
}),
holidays: { '2026-01-01': [{ name: 'stale', localName: 'stale', color: '#000', label: null }] },
});
server.use(http.get('/api/addons/vacay/holidays/:year/:country', () => {
fetched();
return HttpResponse.json([]);
}));
await useVacayStore.getState().loadHolidays(2026);
expect(fetched).not.toHaveBeenCalled();
expect(useVacayStore.getState().holidays).toEqual({});
});
});
+152
View File
@@ -0,0 +1,152 @@
// FE-SYNC-PROBE-001 to FE-SYNC-PROBE-008
// Covers the subscription/lifecycle half of connectivity.ts; the probe-state
// matrix lives in tests/unit/sync/connectivity.test.ts.
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { isReachable, onChange, probeNow, startConnectivityProbe } from './connectivity'
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, configurable: true })
}
function fetchReturns(res: Partial<Response>): void {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(res as Response))
}
const okHealth: Partial<Response> = {
type: 'basic',
ok: true,
headers: new Headers({ 'content-type': 'application/json' }),
}
beforeEach(() => {
setOnline(true)
fetchReturns(okHealth)
})
afterEach(async () => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
vi.useRealTimers()
setOnline(true)
})
describe('connectivity — reachability subscriptions', () => {
it('FE-SYNC-PROBE-001: a subscriber is notified when reachability flips, once per change', async () => {
fetchReturns(okHealth)
await probeNow()
const seen: boolean[] = []
const off = onChange(v => seen.push(v))
setOnline(false)
await probeNow()
await probeNow()
expect(seen).toEqual([false])
expect(isReachable()).toBe(false)
setOnline(true)
fetchReturns(okHealth)
await probeNow()
expect(seen).toEqual([false, true])
expect(isReachable()).toBe(true)
off()
})
it('FE-SYNC-PROBE-002: the returned unsubscribe stops further notifications', async () => {
fetchReturns(okHealth)
await probeNow()
const fn = vi.fn()
const off = onChange(fn)
off()
setOnline(false)
await probeNow()
expect(fn).not.toHaveBeenCalled()
expect(isReachable()).toBe(false)
})
it('FE-SYNC-PROBE-003: a proxy wall counts as unreachable', async () => {
fetchReturns(okHealth)
await probeNow()
fetchReturns({ type: 'opaqueredirect', ok: false, headers: new Headers() })
expect(await probeNow()).toBe('proxy-wall')
expect(isReachable()).toBe(false)
})
})
// startConnectivityProbe installs a permanent interval + window listeners, so
// these run on fake timers to keep the interval out of the other tests.
describe('connectivity — startConnectivityProbe', () => {
it('FE-SYNC-PROBE-004: probes /api/health immediately on start', async () => {
vi.useFakeTimers()
const probeFetch = vi.fn().mockResolvedValue(okHealth as Response)
vi.stubGlobal('fetch', probeFetch)
startConnectivityProbe()
await vi.advanceTimersByTimeAsync(0)
expect(probeFetch).toHaveBeenCalledWith('/api/health', expect.objectContaining({
cache: 'no-store',
credentials: 'include',
redirect: 'manual',
}))
expect(isReachable()).toBe(true)
})
it('FE-SYNC-PROBE-005: re-probes on the 30s interval', async () => {
vi.useFakeTimers()
const probeFetch = vi.fn().mockResolvedValue(okHealth as Response)
vi.stubGlobal('fetch', probeFetch)
startConnectivityProbe()
await vi.advanceTimersByTimeAsync(0)
const afterStart = probeFetch.mock.calls.length
await vi.advanceTimersByTimeAsync(30_000)
expect(probeFetch.mock.calls.length).toBeGreaterThan(afterStart)
})
it('FE-SYNC-PROBE-006: the browser offline event marks us unreachable without a request', async () => {
vi.useFakeTimers()
const probeFetch = vi.fn().mockResolvedValue(okHealth as Response)
vi.stubGlobal('fetch', probeFetch)
startConnectivityProbe()
await vi.advanceTimersByTimeAsync(0)
expect(isReachable()).toBe(true)
probeFetch.mockClear()
window.dispatchEvent(new Event('offline'))
expect(isReachable()).toBe(false)
expect(probeFetch).not.toHaveBeenCalled()
})
it('FE-SYNC-PROBE-007: the browser online event triggers a fresh probe', async () => {
vi.useFakeTimers()
const probeFetch = vi.fn().mockResolvedValue(okHealth as Response)
vi.stubGlobal('fetch', probeFetch)
startConnectivityProbe()
await vi.advanceTimersByTimeAsync(0)
window.dispatchEvent(new Event('offline'))
expect(isReachable()).toBe(false)
window.dispatchEvent(new Event('online'))
await vi.advanceTimersByTimeAsync(0)
expect(isReachable()).toBe(true)
})
it('FE-SYNC-PROBE-008: an aborted health check (timeout) reads as offline', async () => {
vi.stubGlobal('fetch', vi.fn().mockRejectedValue(Object.assign(new Error('aborted'), { name: 'AbortError' })))
expect(await probeNow()).toBe('offline')
expect(isReachable()).toBe(false)
})
})
@@ -0,0 +1,327 @@
// FE-SYNC-PREP-001 to FE-SYNC-PREP-020
// prepareForOffline, the idle tile pass and the file-blob caching branches that
// tests/unit/sync/tripSyncManager.test.ts leaves untouched.
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import 'fake-indexeddb/auto'
import { http, HttpResponse } from 'msw'
import { server } from '../../tests/helpers/msw/server'
import { tripSyncManager, type PrepareProgress } from './tripSyncManager'
import { prefetchTilesForTrip } from './tilePrefetcher'
import { setAuthed } from './authGate'
import { setCacheTiles, setTripOfflineEnabled, _resetOfflinePrefs } from './offlinePrefs'
import { offlineDb, clearAll, upsertTrip } from '../db/offlineDb'
import { buildTrip, buildDay, buildPlace, buildTripFile } from '../../tests/helpers/factories'
import type { Trip, TripFile } from '../types'
vi.mock('./tilePrefetcher', () => ({
prefetchTilesForTrip: vi.fn(async () => {}),
}))
const prefetchMock = vi.mocked(prefetchTilesForTrip)
function dateOffset(days: number): string {
const d = new Date()
d.setDate(d.getDate() + days)
return d.toISOString().slice(0, 10)
}
function bundleFor(trip: Trip, files: TripFile[] = []) {
return {
trip,
days: [buildDay({ trip_id: trip.id })],
places: [buildPlace({ trip_id: trip.id, lat: 48.1, lng: 11.5 })],
packingItems: [],
todoItems: [],
budgetItems: [],
reservations: [],
files,
accommodations: [],
members: [{ id: 1, username: 'ana', role: 'owner' }],
}
}
function serveTrips(trips: Trip[], bundles: Record<number, unknown>): void {
server.use(
http.get('/api/trips', () => HttpResponse.json({ trips })),
http.get('/api/trips/:id/bundle', ({ params }) => {
const bundle = bundles[Number(params.id)]
return bundle ? HttpResponse.json(bundle) : HttpResponse.json({ error: 'nope' }, { status: 500 })
}),
)
}
function setOnline(v: boolean): void {
Object.defineProperty(navigator, 'onLine', { value: v, writable: true, configurable: true })
}
beforeEach(async () => {
await clearAll()
tripSyncManager._resetSyncing()
_resetOfflinePrefs()
setAuthed(true)
setOnline(true)
prefetchMock.mockClear()
prefetchMock.mockResolvedValue(undefined)
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
ok: true,
blob: async () => new Blob(['pdf-bytes'], { type: 'application/pdf' }),
}))
vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
_resetOfflinePrefs()
setAuthed(false)
})
describe('tripSyncManager.prepareForOffline — guards', () => {
it('FE-SYNC-PREP-001: returns 0 and hits no endpoint when logged out', async () => {
setAuthed(false)
let called = false
server.use(http.get('/api/trips', () => { called = true; return HttpResponse.json({ trips: [] }) }))
expect(await tripSyncManager.prepareForOffline()).toBe(0)
expect(called).toBe(false)
})
it('FE-SYNC-PREP-002: returns 0 when the browser is offline', async () => {
setOnline(false)
expect(await tripSyncManager.prepareForOffline()).toBe(0)
})
it('FE-SYNC-PREP-003: a second concurrent run is refused by the syncing flag', async () => {
const trip = buildTrip({ id: 600, end_date: dateOffset(4) })
serveTrips([trip], { 600: bundleFor(trip) })
const [first, second] = await Promise.all([
tripSyncManager.prepareForOffline(),
tripSyncManager.prepareForOffline(),
])
expect([first, second].sort()).toEqual([0, 1])
})
})
describe('tripSyncManager.prepareForOffline — full run', () => {
it('FE-SYNC-PREP-004: reports every phase in order and returns the trip count', async () => {
const trip = buildTrip({ id: 601, title: 'Munich', end_date: dateOffset(4) })
const file = buildTripFile({ id: 900, trip_id: 601, url: '/api/trips/601/files/900/download', mime_type: 'application/pdf' })
serveTrips([trip], { 601: bundleFor(trip, [file]) })
const progress: PrepareProgress[] = []
const count = await tripSyncManager.prepareForOffline(p => progress.push(p))
expect(count).toBe(1)
expect(progress.map(p => p.phase)).toEqual(['trips', 'files', 'tiles', 'done'])
expect(progress[0]).toMatchObject({ current: 1, total: 1, label: 'Munich' })
expect(progress[3]).toMatchObject({ phase: 'done', current: 1, total: 1 })
})
it('FE-SYNC-PREP-005: awaits the bundle, the blobs and the tiles before resolving', async () => {
const trip = buildTrip({ id: 602, end_date: dateOffset(4) })
const file = buildTripFile({ id: 901, trip_id: 602, url: '/api/trips/602/files/901/download', mime_type: 'application/pdf' })
serveTrips([trip], { 602: bundleFor(trip, [file]) })
await tripSyncManager.prepareForOffline()
expect(await offlineDb.trips.get(602)).toBeDefined()
expect(await offlineDb.places.where('trip_id').equals(602).count()).toBe(1)
expect((await offlineDb.blobCache.get('/api/trips/602/files/901/download'))!.mime).toBe('application/pdf')
expect(await offlineDb.tripMembers.where('tripId').equals(602).count()).toBe(1)
})
it('FE-SYNC-PREP-006: forces the tile prefetch so an already-cached bbox is refreshed', async () => {
const trip = buildTrip({ id: 603, end_date: dateOffset(4) })
serveTrips([trip], { 603: bundleFor(trip) })
await tripSyncManager.prepareForOffline()
expect(prefetchMock).toHaveBeenCalledTimes(1)
const [tripId, places, , force] = prefetchMock.mock.calls[0]
expect(tripId).toBe(603)
expect(places).toHaveLength(1)
expect(force).toBe(true)
})
it('FE-SYNC-PREP-007: skips the tile phase when the user turned map tiles off', async () => {
setCacheTiles(false)
const trip = buildTrip({ id: 604, end_date: dateOffset(4) })
serveTrips([trip], { 604: bundleFor(trip) })
const progress: PrepareProgress[] = []
await tripSyncManager.prepareForOffline(p => progress.push(p))
expect(progress.map(p => p.phase)).toEqual(['trips', 'files', 'done'])
expect(prefetchMock).not.toHaveBeenCalled()
})
it('FE-SYNC-PREP-008: caches the global tags and categories', async () => {
const trip = buildTrip({ id: 605, end_date: dateOffset(4) })
serveTrips([trip], { 605: bundleFor(trip) })
await tripSyncManager.prepareForOffline()
expect(await offlineDb.tags.count()).toBeGreaterThan(0)
expect(await offlineDb.categories.count()).toBeGreaterThan(0)
})
it('FE-SYNC-PREP-009: a failing tag/category fetch does not abort the run', async () => {
const trip = buildTrip({ id: 606, end_date: dateOffset(4) })
serveTrips([trip], { 606: bundleFor(trip) })
server.use(
http.get('/api/tags', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
http.get('/api/categories', () => HttpResponse.json({ error: 'boom' }, { status: 500 })),
)
expect(await tripSyncManager.prepareForOffline()).toBe(1)
expect(await offlineDb.tags.count()).toBe(0)
})
it('FE-SYNC-PREP-010: one broken bundle is logged and the other trips still get prepared', async () => {
const good = buildTrip({ id: 607, end_date: dateOffset(4) })
const broken = buildTrip({ id: 608, end_date: dateOffset(4) })
serveTrips([broken, good], { 607: bundleFor(good) })
expect(await tripSyncManager.prepareForOffline()).toBe(2)
expect(await offlineDb.trips.get(607)).toBeDefined()
expect(await offlineDb.trips.get(608)).toBeUndefined()
expect(console.error).toHaveBeenCalled()
})
it('FE-SYNC-PREP-011: evicts a trip the user excluded from offline storage', async () => {
const kept = buildTrip({ id: 609, end_date: dateOffset(4) })
const excluded = buildTrip({ id: 610, end_date: dateOffset(4) })
await upsertTrip(excluded)
setTripOfflineEnabled(610, false)
serveTrips([kept, excluded], { 609: bundleFor(kept), 610: bundleFor(excluded) })
expect(await tripSyncManager.prepareForOffline()).toBe(1)
expect(await offlineDb.trips.get(609)).toBeDefined()
expect(await offlineDb.trips.get(610)).toBeUndefined()
})
})
describe('tripSyncManager — file blob caching', () => {
async function prepareWithFiles(tripId: number, files: TripFile[]): Promise<void> {
const trip = buildTrip({ id: tripId, end_date: dateOffset(4) })
serveTrips([trip], { [tripId]: bundleFor(trip, files) })
await tripSyncManager.prepareForOffline()
}
it('FE-SYNC-PREP-012: an already-cached blob is counted but not re-downloaded', async () => {
const url = '/api/trips/611/files/902/download'
await offlineDb.blobCache.put({ url, tripId: 611, blob: new Blob(['old']), bytes: 3, mime: 'application/pdf', cachedAt: 1 })
await prepareWithFiles(611, [buildTripFile({ id: 902, trip_id: 611, url, mime_type: 'application/pdf' })])
expect(vi.mocked(fetch)).not.toHaveBeenCalled()
expect((await offlineDb.blobCache.get(url))!.cachedAt).toBe(1)
expect((await offlineDb.syncMeta.get(611))!.filesCachedCount).toBe(1)
})
it('FE-SYNC-PREP-013: a non-ok download is skipped and not counted', async () => {
vi.mocked(fetch).mockResolvedValue({ ok: false } as unknown as Response)
await prepareWithFiles(612, [buildTripFile({ id: 903, trip_id: 612, url: '/api/trips/612/files/903/download', mime_type: 'application/pdf' })])
expect(await offlineDb.blobCache.count()).toBe(0)
expect((await offlineDb.syncMeta.get(612))!.filesCachedCount).toBe(0)
})
it('FE-SYNC-PREP-014: a throwing download leaves the rest of the sync intact', async () => {
vi.mocked(fetch).mockRejectedValue(new TypeError('Failed to fetch'))
await prepareWithFiles(613, [buildTripFile({ id: 904, trip_id: 613, url: '/api/trips/613/files/904/download', mime_type: 'application/pdf' })])
expect(await offlineDb.blobCache.count()).toBe(0)
expect(await offlineDb.trips.get(613)).toBeDefined()
})
it('FE-SYNC-PREP-015: photos and videos are never pulled into the bounded blob cache', async () => {
await prepareWithFiles(614, [
buildTripFile({ id: 905, trip_id: 614, url: '/api/trips/614/files/905/download', mime_type: 'image/jpeg' }),
buildTripFile({ id: 906, trip_id: 614, url: '/api/trips/614/files/906/download', mime_type: 'video/mp4' }),
buildTripFile({ id: 907, trip_id: 614, url: '/api/trips/614/files/907/download', mime_type: 'application/pdf' }),
])
const cached = await offlineDb.blobCache.toArray()
expect(cached.map(e => e.url)).toEqual(['/api/trips/614/files/907/download'])
expect((await offlineDb.syncMeta.get(614))!.filesCachedCount).toBe(1)
})
it('FE-SYNC-PREP-016: a file row without a url is ignored', async () => {
await prepareWithFiles(615, [
buildTripFile({ id: 908, trip_id: 615, url: undefined, mime_type: 'application/pdf' }),
])
expect(await offlineDb.blobCache.count()).toBe(0)
})
})
describe('tripSyncManager.syncAll — per-trip failures', () => {
it('FE-SYNC-PREP-020: a failing bundle is logged and the remaining trips still sync', async () => {
setCacheTiles(false)
const good = buildTrip({ id: 619, end_date: dateOffset(4) })
const broken = buildTrip({ id: 620, end_date: dateOffset(4) })
serveTrips([broken, good], { 619: bundleFor(good) })
await tripSyncManager.syncAll()
expect(await offlineDb.trips.get(619)).toBeDefined()
expect(await offlineDb.trips.get(620)).toBeUndefined()
expect(console.error).toHaveBeenCalled()
})
})
describe('tripSyncManager.syncAll — background tile pass', () => {
// jsdom has no requestIdleCallback, so whenIdle falls back to a 2s timeout.
// Stub it with an immediate macrotask to exercise the idle branch.
function stubIdle(): ReturnType<typeof vi.fn> {
const idle = vi.fn((cb: IdleRequestCallback) => {
setTimeout(() => cb({ didTimeout: false, timeRemaining: () => 0 }), 0)
return 1
})
vi.stubGlobal('requestIdleCallback', idle)
return idle
}
it('FE-SYNC-PREP-017: prefetches tiles once the browser goes idle', async () => {
const idle = stubIdle()
const trip = buildTrip({ id: 616, end_date: dateOffset(4) })
serveTrips([trip], { 616: bundleFor(trip) })
await tripSyncManager.syncAll()
await new Promise(r => setTimeout(r, 50))
expect(idle).toHaveBeenCalled()
expect(prefetchMock).toHaveBeenCalledTimes(1)
expect(prefetchMock.mock.calls[0][0]).toBe(616)
// syncAll must not force — a routine login should skip an unchanged bbox.
expect(prefetchMock.mock.calls[0][3]).toBeUndefined()
})
it('FE-SYNC-PREP-018: a logout between sync and idle time cancels the tile pass', async () => {
stubIdle()
const trip = buildTrip({ id: 617, end_date: dateOffset(4) })
serveTrips([trip], { 617: bundleFor(trip) })
await tripSyncManager.syncAll()
setAuthed(false)
await new Promise(r => setTimeout(r, 50))
expect(prefetchMock).not.toHaveBeenCalled()
})
it('FE-SYNC-PREP-019: going offline between sync and idle time cancels the tile pass', async () => {
stubIdle()
const trip = buildTrip({ id: 618, end_date: dateOffset(4) })
serveTrips([trip], { 618: bundleFor(trip) })
await tripSyncManager.syncAll()
setOnline(false)
await new Promise(r => setTimeout(r, 50))
expect(prefetchMock).not.toHaveBeenCalled()
})
})
+206
View File
@@ -0,0 +1,206 @@
// FE-THEME-APPLY-001 to FE-THEME-APPLY-014
import { APPEARANCE_SNAPSHOT_KEY, applyAppearance, clearAppearanceSnapshot } from './applyAppearance';
const root = document.documentElement;
function snapshot(): Record<string, unknown> {
return JSON.parse(localStorage.getItem(APPEARANCE_SNAPSHOT_KEY) ?? '{}');
}
beforeEach(() => {
root.className = '';
root.removeAttribute('style');
for (const attr of ['data-scheme', 'data-no-transparency', 'data-density', 'data-reduce-motion']) {
root.removeAttribute(attr);
}
document.head.innerHTML = '';
});
describe('applyAppearance', () => {
it('FE-THEME-APPLY-001: the default config leaves every marker attribute off', () => {
applyAppearance({ darkMode: false });
expect(root.classList.contains('dark')).toBe(false);
expect(root.hasAttribute('data-scheme')).toBe(false);
expect(root.hasAttribute('data-no-transparency')).toBe(false);
expect(root.hasAttribute('data-density')).toBe(false);
expect(root.hasAttribute('data-reduce-motion')).toBe(false);
expect(root.style.getPropertyValue('--fs-scale-body')).toBe('');
expect(root.style.fontSize).toBe('');
});
it('FE-THEME-APPLY-002: toggles the dark class for the boolean and string forms', () => {
applyAppearance({ darkMode: true });
expect(root.classList.contains('dark')).toBe(true);
applyAppearance({ darkMode: 'light' });
expect(root.classList.contains('dark')).toBe(false);
applyAppearance({ darkMode: 'dark' });
expect(root.classList.contains('dark')).toBe(true);
});
it('FE-THEME-APPLY-003: auto follows the OS preference', () => {
vi.mocked(window.matchMedia).mockReturnValueOnce({ matches: true } as unknown as MediaQueryList);
applyAppearance({ darkMode: 'auto' });
expect(root.classList.contains('dark')).toBe(true);
vi.mocked(window.matchMedia).mockReturnValueOnce({ matches: false } as unknown as MediaQueryList);
applyAppearance({ darkMode: 'auto' });
expect(root.classList.contains('dark')).toBe(false);
});
it('FE-THEME-APPLY-004: a shared page renders light and neutral no matter what the account wants', () => {
const cfg = applyAppearance({
darkMode: 'dark',
appearance: { schemeId: 'custom', accent: { light: '#ff0000', dark: '#ff0000' }, transparency: false },
isSharedPage: true,
});
expect(root.classList.contains('dark')).toBe(false);
expect(root.hasAttribute('data-scheme')).toBe(false);
expect(root.hasAttribute('data-no-transparency')).toBe(false);
expect(root.style.getPropertyValue('--accent-custom-light')).toBe('');
// The returned config is still the user's own — only the DOM is neutralised.
expect(cfg.schemeId).toBe('custom');
});
it('FE-THEME-APPLY-005: writes data-scheme for a non-default scheme and clears it again', () => {
applyAppearance({ darkMode: false, appearance: { schemeId: 'indigo' } });
expect(root.getAttribute('data-scheme')).toBe('indigo');
applyAppearance({ darkMode: false });
expect(root.hasAttribute('data-scheme')).toBe(false);
});
it('FE-THEME-APPLY-006: marks transparency being switched off', () => {
applyAppearance({ darkMode: false, appearance: { transparency: false } });
expect(root.hasAttribute('data-no-transparency')).toBe(true);
applyAppearance({ darkMode: false, appearance: { transparency: true } });
expect(root.hasAttribute('data-no-transparency')).toBe(false);
});
it('FE-THEME-APPLY-007: only compact density sets an attribute', () => {
applyAppearance({ darkMode: false, appearance: { density: 'compact' } });
expect(root.getAttribute('data-density')).toBe('compact');
applyAppearance({ darkMode: false, appearance: { density: 'comfortable' } });
expect(root.hasAttribute('data-density')).toBe(false);
});
it('FE-THEME-APPLY-008: mirrors the reduce-motion override', () => {
applyAppearance({ darkMode: false, appearance: { reduceMotion: true } });
expect(root.hasAttribute('data-reduce-motion')).toBe(true);
applyAppearance({ darkMode: false, appearance: { reduceMotion: false } });
expect(root.hasAttribute('data-reduce-motion')).toBe(false);
});
it('FE-THEME-APPLY-009: a custom accent writes the four inline vars', () => {
applyAppearance({
darkMode: false,
appearance: { schemeId: 'custom', accent: { light: '#4f46e5', dark: '#818cf8' } },
});
expect(root.style.getPropertyValue('--accent-custom-light')).toBe('#4f46e5');
expect(root.style.getPropertyValue('--accent-custom-dark')).toBe('#818cf8');
});
it('FE-THEME-APPLY-010: derives a legible accent text colour from the luminance', () => {
applyAppearance({
darkMode: false,
// dark fill -> white text, near-white fill -> near-black text
appearance: { schemeId: 'custom', accent: { light: '#111827', dark: '#f8fafc' } },
});
expect(root.style.getPropertyValue('--accent-custom-text-light')).toBe('#ffffff');
expect(root.style.getPropertyValue('--accent-custom-text-dark')).toBe('#111827');
});
it('FE-THEME-APPLY-011: accepts the three-digit hex shorthand', () => {
applyAppearance({
darkMode: false,
appearance: { schemeId: 'custom', accent: { light: '#fff', dark: '#000' } },
});
expect(root.style.getPropertyValue('--accent-custom-text-light')).toBe('#111827');
expect(root.style.getPropertyValue('--accent-custom-text-dark')).toBe('#ffffff');
});
it('FE-THEME-APPLY-012: removes the accent vars when the scheme leaves custom', () => {
applyAppearance({
darkMode: false,
appearance: { schemeId: 'custom', accent: { light: '#4f46e5', dark: '#818cf8' } },
});
applyAppearance({ darkMode: false, appearance: { schemeId: 'default' } });
expect(root.style.getPropertyValue('--accent-custom-light')).toBe('');
expect(root.style.getPropertyValue('--accent-custom-text-dark')).toBe('');
});
it('FE-THEME-APPLY-013: writes the scale vars and root font-size only when they deviate from 1', () => {
applyAppearance({ darkMode: false, appearance: { fontScale: 1.2 } });
expect(root.style.getPropertyValue('--fs-scale-title')).toBe('1.2');
expect(root.style.getPropertyValue('--fs-scale-body')).toBe('1.2');
expect(root.style.fontSize).toBe('120%');
applyAppearance({ darkMode: false, appearance: { fontScale: 1 } });
expect(root.style.getPropertyValue('--fs-scale-title')).toBe('');
expect(root.style.fontSize).toBe('');
});
it('FE-THEME-APPLY-014: updates the theme-color meta tag when one is present', () => {
const meta = document.createElement('meta');
meta.setAttribute('name', 'theme-color');
meta.setAttribute('content', '#ffffff');
document.head.appendChild(meta);
applyAppearance({ darkMode: true });
expect(meta.getAttribute('content')).toBe('#09090b');
applyAppearance({ darkMode: false });
expect(meta.getAttribute('content')).toBe('#ffffff');
});
});
describe('appearance snapshot', () => {
it('FE-THEME-APPLY-015: persists the resolved state for the pre-paint boot script', () => {
applyAppearance({
darkMode: 'dark',
appearance: { schemeId: 'custom', accent: { light: '#111827', dark: '#f8fafc' }, transparency: false, density: 'compact' },
});
const snap = snapshot();
expect(snap.v).toBe(1);
expect(snap.darkMode).toBe('dark');
expect(snap.scheme).toBe('custom');
expect(snap.noTransparency).toBe(true);
expect(snap.density).toBe('compact');
expect(snap.accentText).toEqual({ light: '#ffffff', dark: '#111827' });
});
it('FE-THEME-APPLY-016: clearAppearanceSnapshot drops the stored snapshot', () => {
applyAppearance({ darkMode: false });
expect(localStorage.getItem(APPEARANCE_SNAPSHOT_KEY)).not.toBeNull();
clearAppearanceSnapshot();
expect(localStorage.getItem(APPEARANCE_SNAPSHOT_KEY)).toBeNull();
});
it('FE-THEME-APPLY-017: a storage failure stays non-fatal', () => {
const setItem = vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
throw new DOMException('quota', 'QuotaExceededError');
});
const removeItem = vi.spyOn(Storage.prototype, 'removeItem').mockImplementation(() => {
throw new DOMException('quota', 'QuotaExceededError');
});
expect(() => applyAppearance({ darkMode: false })).not.toThrow();
expect(() => clearAppearanceSnapshot()).not.toThrow();
setItem.mockRestore();
removeItem.mockRestore();
});
});
+35
View File
@@ -0,0 +1,35 @@
// FE-W4UTL-001 to FE-W4UTL-006
import { describe, it, expect } from 'vitest'
import { getApiErrorMessage } from './apiError'
describe('getApiErrorMessage', () => {
it('FE-W4UTL-001: returns the server-provided error string', () => {
const err = { response: { data: { error: 'Places API (New) has not been used in project 42' } } }
expect(getApiErrorMessage(err, 'fallback')).toBe('Places API (New) has not been used in project 42')
})
it('FE-W4UTL-002: falls back when the error field is missing', () => {
expect(getApiErrorMessage({ response: { data: {} } }, 'fallback')).toBe('fallback')
expect(getApiErrorMessage({ response: {} }, 'fallback')).toBe('fallback')
expect(getApiErrorMessage({}, 'fallback')).toBe('fallback')
})
it('FE-W4UTL-003: falls back for null/undefined errors', () => {
expect(getApiErrorMessage(null, 'fallback')).toBe('fallback')
expect(getApiErrorMessage(undefined, 'fallback')).toBe('fallback')
})
it('FE-W4UTL-004: falls back for a whitespace-only server message', () => {
expect(getApiErrorMessage({ response: { data: { error: ' ' } } }, 'fallback')).toBe('fallback')
expect(getApiErrorMessage({ response: { data: { error: '' } } }, 'fallback')).toBe('fallback')
})
it('FE-W4UTL-005: falls back for a non-string server message', () => {
expect(getApiErrorMessage({ response: { data: { error: { code: 500 } } } }, 'fallback')).toBe('fallback')
expect(getApiErrorMessage({ response: { data: { error: 42 } } }, 'fallback')).toBe('fallback')
})
it('FE-W4UTL-006: keeps surrounding whitespace of a real message', () => {
expect(getApiErrorMessage({ response: { data: { error: ' boom ' } } }, 'fallback')).toBe(' boom ')
})
})
+79
View File
@@ -0,0 +1,79 @@
// FE-W4HEIC-001 to FE-W4HEIC-007
import { describe, it, expect, vi, beforeEach } from 'vitest'
const isHeic = vi.fn(async (_f: File) => true)
const heicTo = vi.fn(async (_opts: unknown) => new Blob(['jpeg'], { type: 'image/jpeg' }))
vi.mock('heic-to', () => ({
isHeic: (f: File) => isHeic(f),
heicTo: (opts: unknown) => heicTo(opts),
}))
import { normalizeImageFile, normalizeImageFiles } from './convertHeic'
beforeEach(() => {
isHeic.mockClear()
heicTo.mockClear()
isHeic.mockResolvedValue(true)
})
describe('normalizeImageFile', () => {
it('FE-W4HEIC-001: passes a plain jpeg straight through', async () => {
const f = new File(['x'], 'photo.jpg', { type: 'image/jpeg' })
await expect(normalizeImageFile(f)).resolves.toBe(f)
expect(isHeic).not.toHaveBeenCalled()
})
it('FE-W4HEIC-002: converts a .heic file to jpeg and renames it', async () => {
const f = new File(['x'], 'IMG_0042.HEIC', { type: '' })
const out = await normalizeImageFile(f)
expect(out).not.toBe(f)
expect(out.name).toBe('IMG_0042.jpg')
expect(out.type).toBe('image/jpeg')
expect(heicTo).toHaveBeenCalledWith({ blob: f, type: 'image/jpeg', quality: 0.92 })
})
it('FE-W4HEIC-003: converts a .heif file too', async () => {
const out = await normalizeImageFile(new File(['x'], 'scan.heif'))
expect(out.name).toBe('scan.jpg')
})
it('FE-W4HEIC-004: detects heic by mime type when the name has no extension', async () => {
const f = new File(['x'], 'clipboard', { type: 'image/heic' })
const out = await normalizeImageFile(f)
expect(heicTo).toHaveBeenCalled()
// No .heic/.heif suffix to strip, so the name stays as-is.
expect(out.name).toBe('clipboard')
expect(out.type).toBe('image/jpeg')
})
it('FE-W4HEIC-005: returns the original when the magic bytes say it is not heic', async () => {
isHeic.mockResolvedValue(false)
const f = new File(['x'], 'mislabelled.heic')
await expect(normalizeImageFile(f)).resolves.toBe(f)
expect(heicTo).not.toHaveBeenCalled()
})
})
describe('normalizeImageFiles', () => {
it('FE-W4HEIC-006: normalizes a mixed list and keeps the order', async () => {
const jpg = new File(['x'], 'a.jpg', { type: 'image/jpeg' })
const heic = new File(['x'], 'b.heic')
const out = await normalizeImageFiles([jpg, heic])
expect(out).toHaveLength(2)
expect(out[0]).toBe(jpg)
expect(out[1].name).toBe('b.jpg')
})
it('FE-W4HEIC-007: accepts a FileList-like object', async () => {
const jpg = new File(['x'], 'a.jpg', { type: 'image/jpeg' })
const fakeList = { 0: jpg, length: 1 } as unknown as FileList
await expect(normalizeImageFiles(fakeList)).resolves.toEqual([jpg])
})
})
@@ -0,0 +1,88 @@
// FE-W4LOC-001 to FE-W4LOC-014
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
import { formatLocationName, formatDate, formatTime } from './formatters'
describe('formatLocationName', () => {
it('FE-W4LOC-001: returns an empty string for a missing name', () => {
expect(formatLocationName(null)).toBe('')
expect(formatLocationName(undefined)).toBe('')
expect(formatLocationName('')).toBe('')
})
it('FE-W4LOC-002: passes a short name through untouched', () => {
expect(formatLocationName(' Blue Lagoon, Grindavík, Iceland ')).toBe('Blue Lagoon, Grindavík, Iceland')
expect(formatLocationName('Reykjavik')).toBe('Reykjavik')
})
it('FE-W4LOC-003: collapses a verbose Nominatim string to name, postcode, country', () => {
const raw = 'Hallgrimskirkja, 1, Skolavorduholt, Midborg, Reykjavik, Capital Region, Iceland, 101'
expect(formatLocationName(raw)).toBe('Hallgrimskirkja, 101, Iceland')
})
it('FE-W4LOC-004: drops the postcode when the tail is not one', () => {
const raw = 'Blue Lagoon, Norðurljósavegur, Grindavík, Southern Peninsula, Iceland'
expect(formatLocationName(raw)).toBe('Blue Lagoon, Iceland')
})
it('FE-W4LOC-005: deduplicates repeated parts before shortening', () => {
expect(formatLocationName('Paris, Paris, Paris, France')).toBe('Paris, France')
})
it('FE-W4LOC-006: keeps a deduplicated list of three or fewer parts intact', () => {
expect(formatLocationName('A, A, B, C')).toBe('A, B, C')
})
it('FE-W4LOC-007: never repeats the name as country or postcode', () => {
expect(formatLocationName('101, Skolavorduholt, Midborg, Reykjavik, 101')).toBe('101, Reykjavik')
})
it('FE-W4LOC-008: rejects an over-long tail as a postcode', () => {
const raw = 'Museum, Street, District, City, Region, Country, 1234567890AB'
expect(formatLocationName(raw)).toBe('Museum, 1234567890AB')
})
})
describe('formatDate', () => {
beforeAll(() => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-06-15T12:00:00Z'))
})
afterAll(() => {
vi.useRealTimers()
})
it('FE-W4LOC-009: omits the year for a date in the current year', () => {
const out = formatDate('2026-08-01', 'en-US')
expect(out).toContain('Aug')
expect(out).not.toContain('2026')
})
it('FE-W4LOC-010: adds the year for another year and returns null without a date', () => {
expect(formatDate('2025-08-01', 'en-US')).toContain('2025')
expect(formatDate(null, 'en-US')).toBeNull()
expect(formatDate('', 'en-US')).toBeNull()
})
})
describe('formatTime', () => {
it('FE-W4LOC-011: renders a padded 24h time', () => {
expect(formatTime('9:05', 'en-US', '24h')).toBe('09:05')
expect(formatTime('', 'en-US', '24h')).toBe('')
})
it('FE-W4LOC-012: appends Uhr for German locales', () => {
expect(formatTime('18:30', 'de-DE', '24h')).toBe('18:30 Uhr')
})
it('FE-W4LOC-013: renders a 12h time with the right period', () => {
expect(formatTime('00:15', 'en-US', '12h')).toBe('12:15 AM')
expect(formatTime('12:00', 'en-US', '12h')).toBe('12:00 PM')
expect(formatTime('13:05', 'en-US', '12h')).toBe('1:05 PM')
expect(formatTime('09:00', 'en-US', '12h')).toBe('9:00 AM')
})
it('FE-W4LOC-014: treats unparseable parts as zero', () => {
expect(formatTime('abc', 'en-US', '24h')).toBe('00:00')
})
})
+31
View File
@@ -0,0 +1,31 @@
// FE-W4UTL-010 to FE-W4UTL-014
import { describe, it, expect } from 'vitest'
import { GRADIENTS, entityGradient } from './gradients'
describe('entityGradient', () => {
it('FE-W4UTL-010: exposes eight two-stop gradients', () => {
expect(GRADIENTS).toHaveLength(8)
GRADIENTS.forEach(g => expect(g).toMatch(/^linear-gradient\(135deg, #[0-9a-f]{6} 0%, #[0-9a-f]{6} 100%\)$/))
})
it('FE-W4UTL-011: maps an id onto its slot', () => {
expect(entityGradient(0)).toBe(GRADIENTS[0])
expect(entityGradient(3)).toBe(GRADIENTS[3])
expect(entityGradient(7)).toBe(GRADIENTS[7])
})
it('FE-W4UTL-012: wraps around past the palette length', () => {
expect(entityGradient(8)).toBe(GRADIENTS[0])
expect(entityGradient(11)).toBe(GRADIENTS[3])
})
it('FE-W4UTL-013: handles negative ids without going out of range', () => {
expect(entityGradient(-1)).toBe(GRADIENTS[7])
expect(entityGradient(-8)).toBe(GRADIENTS[0])
expect(entityGradient(-11)).toBe(GRADIENTS[5])
})
it('FE-W4UTL-014: is stable for the same id', () => {
expect(entityGradient(42)).toBe(entityGradient(42))
})
})
+61
View File
@@ -0,0 +1,61 @@
// FE-W4UTL-020 to FE-W4UTL-029
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
import { computeJourneyLifecycle } from './journeyLifecycle'
const TODAY = '2026-06-15'
beforeAll(() => {
vi.useFakeTimers()
vi.setSystemTime(new Date(`${TODAY}T12:00:00Z`))
})
afterAll(() => {
vi.useRealTimers()
})
describe('computeJourneyLifecycle', () => {
it('FE-W4UTL-020: archived wins over any date range', () => {
expect(computeJourneyLifecycle('archived', '2026-06-01', '2026-06-30')).toBe('archived')
expect(computeJourneyLifecycle('archived', null, null)).toBe('archived')
})
it('FE-W4UTL-021: a range containing today is live', () => {
expect(computeJourneyLifecycle('published', '2026-06-01', '2026-06-30')).toBe('live')
})
it('FE-W4UTL-022: today on either boundary is still live', () => {
expect(computeJourneyLifecycle('published', TODAY, '2026-06-30')).toBe('live')
expect(computeJourneyLifecycle('published', '2026-06-01', TODAY)).toBe('live')
})
it('FE-W4UTL-023: a future range is upcoming', () => {
expect(computeJourneyLifecycle('published', '2026-07-01', '2026-07-10')).toBe('upcoming')
})
it('FE-W4UTL-024: a past range is completed', () => {
expect(computeJourneyLifecycle('published', '2026-05-01', '2026-05-10')).toBe('completed')
})
it('FE-W4UTL-025: no dates at all is a draft', () => {
expect(computeJourneyLifecycle('published', null, null)).toBe('draft')
expect(computeJourneyLifecycle('published', undefined, undefined)).toBe('draft')
})
it('FE-W4UTL-026: start only, in the future, is upcoming', () => {
expect(computeJourneyLifecycle('published', '2026-07-01', null)).toBe('upcoming')
})
it('FE-W4UTL-027: start only, already reached, is live', () => {
expect(computeJourneyLifecycle('published', '2026-06-01', null)).toBe('live')
expect(computeJourneyLifecycle('published', TODAY, null)).toBe('live')
})
it('FE-W4UTL-028: end only, in the past, is completed', () => {
expect(computeJourneyLifecycle('published', null, '2026-05-10')).toBe('completed')
})
it('FE-W4UTL-029: end only, not yet reached, is live', () => {
expect(computeJourneyLifecycle('published', null, '2026-06-30')).toBe('live')
expect(computeJourneyLifecycle('published', null, TODAY)).toBe('live')
})
})
+142
View File
@@ -0,0 +1,142 @@
// FE-W4UPQ-001 to FE-W4UPQ-010
import { describe, it, expect, vi } from 'vitest'
import { uploadFilesResilient, type UploadOpts, type UploadProgress } from './uploadQueue'
function file(name: string, size = 100): File {
const f = new File(['x'], name, { type: 'text/plain' })
Object.defineProperty(f, 'size', { value: size })
return f
}
describe('uploadFilesResilient', () => {
it('FE-W4UPQ-001: returns every uploaded item and no failures', async () => {
const files = [file('a.txt'), file('b.txt')]
const uploadOne = vi.fn(async (f: File) => [{ name: f.name }])
const res = await uploadFilesResilient(files, uploadOne)
expect(res.failed).toEqual([])
expect(res.succeeded).toEqual([{ name: 'a.txt' }, { name: 'b.txt' }])
expect(uploadOne).toHaveBeenCalledTimes(2)
})
it('FE-W4UPQ-002: passes a fresh idempotency key per file', async () => {
const keys: string[] = []
const uploadOne = async (_f: File, opts: UploadOpts) => { keys.push(opts.idempotencyKey); return [] }
await uploadFilesResilient([file('a.txt'), file('b.txt')], uploadOne)
expect(keys).toHaveLength(2)
expect(keys[0]).not.toBe(keys[1])
expect(keys[0]).toMatch(/^[0-9a-f-]{36}$/)
})
it('FE-W4UPQ-003: streams onUploaded per file as it lands', async () => {
const onUploaded = vi.fn()
await uploadFilesResilient(
[file('a.txt'), file('b.txt')],
async (f: File) => [f.name],
{ concurrency: 1, onUploaded },
)
expect(onUploaded).toHaveBeenNthCalledWith(1, ['a.txt'])
expect(onUploaded).toHaveBeenNthCalledWith(2, ['b.txt'])
})
it('FE-W4UPQ-004: reports byte progress from onUploadProgress and finishes at 100%', async () => {
const seen: UploadProgress[] = []
const uploadOne = async (f: File, opts: UploadOpts) => {
opts.onUploadProgress({ loaded: f.size / 2, total: f.size } as never)
return [f.name]
}
await uploadFilesResilient([file('a.txt', 200)], uploadOne, { onProgress: p => { seen.push(p) } })
expect(seen[0]).toEqual({ done: 0, total: 1, failed: 0, percent: 50 })
expect(seen[seen.length - 1]).toEqual({ done: 1, total: 1, failed: 0, percent: 100 })
})
it('FE-W4UPQ-005: reports 0% when the files carry no bytes', async () => {
const seen: UploadProgress[] = []
await uploadFilesResilient([file('a.txt', 0)], async () => [], { onProgress: p => { seen.push(p) } })
expect(seen[seen.length - 1]).toEqual({ done: 1, total: 1, failed: 0, percent: 0 })
})
it('FE-W4UPQ-006: retries a transient failure and keeps the file', async () => {
let calls = 0
const uploadOne = vi.fn(async (f: File) => {
calls++
if (calls === 1) throw new Error('network down')
return [f.name]
})
const res = await uploadFilesResilient([file('a.txt')], uploadOne, { retries: 1 })
expect(calls).toBe(2)
expect(res.succeeded).toEqual(['a.txt'])
expect(res.failed).toEqual([])
})
it('FE-W4UPQ-007: does not retry a 4xx and reports the file as failed', async () => {
const uploadOne = vi.fn(async () => { throw { response: { status: 413 } } })
const f = file('big.txt')
const res = await uploadFilesResilient([f], uploadOne, { retries: 2 })
expect(uploadOne).toHaveBeenCalledTimes(1)
expect(res.succeeded).toEqual([])
expect(res.failed).toEqual([f])
})
it('FE-W4UPQ-008: retries a 5xx up to the limit then gives up', async () => {
const uploadOne = vi.fn(async () => { throw { response: { status: 502 } } })
const f = file('a.txt')
const res = await uploadFilesResilient([f], uploadOne, { retries: 1 })
expect(uploadOne).toHaveBeenCalledTimes(2)
expect(res.failed).toEqual([f])
})
it('FE-W4UPQ-009: a failed file counts into the progress failure tally', async () => {
const seen: UploadProgress[] = []
const ok = file('ok.txt')
const bad = file('bad.txt')
const uploadOne = async (f: File) => {
if (f.name === 'bad.txt') throw { response: { status: 400 } }
return [f.name]
}
const res = await uploadFilesResilient([ok, bad], uploadOne, { concurrency: 1, onProgress: p => { seen.push(p) } })
expect(res.succeeded).toEqual(['ok.txt'])
expect(res.failed).toEqual([bad])
expect(seen[seen.length - 1]).toMatchObject({ done: 1, failed: 1, total: 2 })
})
it('FE-W4UPQ-010: never spawns more workers than files', async () => {
let inFlight = 0
let peak = 0
const uploadOne = async (f: File) => {
inFlight++
peak = Math.max(peak, inFlight)
await Promise.resolve()
inFlight--
return [f.name]
}
const res = await uploadFilesResilient([file('a.txt'), file('b.txt')], uploadOne, { concurrency: 10 })
expect(peak).toBeLessThanOrEqual(2)
expect(res.succeeded).toHaveLength(2)
})
it('FE-W4UPQ-011: an empty file list resolves without calling the uploader', async () => {
const uploadOne = vi.fn(async () => [])
const res = await uploadFilesResilient([], uploadOne)
expect(uploadOne).not.toHaveBeenCalled()
expect(res).toEqual({ succeeded: [], failed: [] })
})
})
+149
View File
@@ -0,0 +1,149 @@
import { vi } from 'vitest';
import type { AtlasController } from '../../src/mobile/screens/atlas/atlasController';
import type { AtlasData, BucketItem, CountryDetail } from '../../src/pages/atlas/atlasModel';
/**
* Fixtures for the atlas surfaces. Desktop page, mobile screen, bucket sheet
* and country popup all consume the same useAtlas() controller, so tests build
* one object here instead of mounting the hook with a Leaflet map behind it.
*
* The state setters are spies that also write the new value back onto the
* controller (including updater callbacks), so a test can assert both "the
* setter was called" and "this is the state it produced".
*/
export type VisitedRegions = Record<string, { code: string; name: string; placeCount: number; manuallyMarked?: boolean }[]>;
const echoT = (key: string, params?: Record<string, string | number>): string =>
params ? `${key}:${Object.values(params).join(',')}` : key;
export function buildAtlasData(over: Partial<AtlasData> = {}): AtlasData {
return {
countries: [{ code: 'FR', tripCount: 2, placeCount: 5, firstVisit: '2023-01-01', lastVisit: '2024-06-01' }],
stats: { totalTrips: 3, totalPlaces: 10, totalCountries: 1, totalDays: 14, totalCities: 3 },
mostVisited: null,
continents: { Europe: 1 },
lastTrip: { id: 7, title: 'Paris Trip', countryCode: 'FR' },
nextTrip: null,
streak: 2,
firstYear: 2022,
tripsThisYear: 1,
...over,
};
}
export function buildBucketItem(over: Partial<BucketItem> = {}): BucketItem {
return {
id: 1,
name: 'Kyoto',
lat: null,
lng: null,
country_code: 'JP',
notes: null,
target_date: null,
...over,
};
}
export function buildCountryDetail(over: Partial<CountryDetail> = {}): CountryDetail {
return {
places: [],
trips: [],
manually_marked: false,
...over,
};
}
/** state field → its setter on the controller. */
const SETTERS: Record<string, string> = {
data: 'setData',
visitedRegions: 'setVisitedRegions',
bucketList: 'setBucketList',
confirmAction: 'setConfirmAction',
bucketForm: 'setBucketForm',
bucketSearch: 'setBucketSearch',
bucketSearchResults: 'setBucketSearchResults',
showBucketAdd: 'setShowBucketAdd',
bucketTab: 'setBucketTab',
bucketMonth: 'setBucketMonth',
bucketYear: 'setBucketYear',
bucketPoiMonth: 'setBucketPoiMonth',
bucketPoiYear: 'setBucketPoiYear',
atlas_country_search: 'set_atlas_country_search',
atlas_country_results: 'set_atlas_country_results',
atlas_country_open: 'set_atlas_country_open',
};
const COUNTRY_NAMES: Record<string, string> = {
AR: 'Argentina', DE: 'Germany', ES: 'Spain', FR: 'France', GR: 'Greece',
IT: 'Italy', JP: 'Japan', PE: 'Peru', PT: 'Portugal', US: 'United States',
};
export function buildAtlasController(over: Record<string, unknown> = {}): AtlasController {
const base: Record<string, unknown> = {
t: echoT,
language: 'en',
navigate: vi.fn(() => undefined),
resolveName: (code: string) => COUNTRY_NAMES[code] ?? code,
dark: false,
loading: false,
mapRef: { current: null },
regionTooltipRef: { current: null },
panelRef: { current: null },
glareRef: { current: null },
borderGlareRef: { current: null },
handlePanelMouseMove: vi.fn(() => undefined),
handlePanelMouseLeave: vi.fn(() => undefined),
data: buildAtlasData(),
stats: buildAtlasData().stats,
countries: buildAtlasData().countries,
selectedCountry: null,
countryDetail: null,
loadCountryDetail: vi.fn(async () => undefined),
handleUnmarkCountry: vi.fn(() => undefined),
select_country_from_search: vi.fn(() => undefined),
visitedRegions: {} as VisitedRegions,
atlas_country_search: '',
atlas_country_results: [],
atlas_country_open: false,
atlas_country_options: [],
confirmAction: null,
executeConfirmAction: vi.fn(async () => undefined),
bucketMonth: 0,
bucketYear: 0,
bucketList: [] as BucketItem[],
bucketTab: 'stats',
showBucketAdd: false,
bucketForm: { name: '', notes: '', lat: '', lng: '', target_date: '' },
handleAddBucketItem: vi.fn(async () => undefined),
handleDeleteBucketItem: vi.fn(async () => undefined),
handleBucketPoiSearch: vi.fn(async () => undefined),
handleSelectBucketPoi: vi.fn(() => undefined),
bucketSearchResults: [],
bucketPoiMonth: 0,
bucketPoiYear: 0,
bucketSearching: false,
bucketSearch: '',
};
const ctrl: Record<string, unknown> = { ...base, ...over };
for (const [field, setter] of Object.entries(SETTERS)) {
if (setter in over) continue;
ctrl[setter] = vi.fn((next: unknown) => {
ctrl[field] = typeof next === 'function' ? (next as (prev: unknown) => unknown)(ctrl[field]) : next;
});
}
// stats/countries mirror data unless a test pinned them explicitly.
const data = ctrl.data as AtlasData | null;
if (!('stats' in over)) ctrl.stats = data?.stats ?? { totalTrips: 0, totalPlaces: 0, totalCountries: 0, totalDays: 0 };
if (!('countries' in over)) ctrl.countries = data?.countries ?? [];
return ctrl as unknown as AtlasController;
}
@@ -0,0 +1,195 @@
// FE-COMP-I18NCTX-001 to FE-COMP-I18NCTX-017
import { act, render, screen, waitFor } from '@testing-library/react';
import { SUPPORTED_LANGUAGES, TranslationProvider, useTranslation } from '../../../src/i18n/TranslationContext';
import { TransHtml } from '../../../src/i18n/TransHtml';
import { useSettingsStore } from '../../../src/store/settingsStore';
import { resetAllStores, seedStore } from '../../helpers/store';
// The provider swaps the whole string table via a dynamic import per locale, so
// these tests assert on what the consumer actually sees rather than on the
// loader plumbing: English is synchronous, everything else arrives one tick later.
function Probe({ tKey, params }: { tKey: string; params?: Record<string, string | number> }) {
const { t, language, locale } = useTranslation();
return (
<div>
<span data-testid="value">{t(tKey, params)}</span>
<span data-testid="language">{language}</span>
<span data-testid="locale">{locale}</span>
</div>
);
}
function HtmlProbe({ tKey, params }: { tKey: string; params?: Record<string, string | number> }) {
const { tHtml } = useTranslation();
return <span data-testid="raw">{tHtml(tKey, params)}</span>;
}
function withLanguage(language: string) {
seedStore(useSettingsStore, { settings: { language } });
}
beforeEach(() => {
resetAllStores();
document.documentElement.lang = '';
document.documentElement.dir = '';
});
describe('TranslationProvider', () => {
it('FE-COMP-I18NCTX-001: resolves a key from the English table', () => {
render(<TranslationProvider><Probe tKey="common.save" /></TranslationProvider>);
expect(screen.getByTestId('value').textContent).toBe('Save');
});
it('FE-COMP-I18NCTX-002: returns the key itself when nothing matches', () => {
render(<TranslationProvider><Probe tKey="does.not.exist" /></TranslationProvider>);
expect(screen.getByTestId('value').textContent).toBe('does.not.exist');
});
it('FE-COMP-I18NCTX-003: substitutes every occurrence of a placeholder', () => {
render(<TranslationProvider><Probe tKey="common.hoursAgo" params={{ count: 5 }} /></TranslationProvider>);
expect(screen.getByTestId('value').textContent).toContain('5');
});
it('FE-COMP-I18NCTX-004: defaults to English with the matching locale', () => {
render(<TranslationProvider><Probe tKey="common.save" /></TranslationProvider>);
expect(screen.getByTestId('language').textContent).toBe('en');
expect(screen.getByTestId('locale').textContent).toBe('en-US');
});
it('FE-COMP-I18NCTX-005: loads another locale and exposes its language and locale', async () => {
withLanguage('de');
render(<TranslationProvider><Probe tKey="common.save" /></TranslationProvider>);
expect(screen.getByTestId('language').textContent).toBe('de');
await waitFor(() => expect(screen.getByTestId('value').textContent).toBe('Speichern'));
expect(screen.getByTestId('locale').textContent).toBe('de-DE');
});
it('FE-COMP-I18NCTX-006: falls back to the English string for a key a locale is missing', async () => {
withLanguage('de');
render(<TranslationProvider><Probe tKey="does.not.exist" /></TranslationProvider>);
await waitFor(() => expect(screen.getByTestId('value').textContent).toBe('does.not.exist'));
});
it('FE-COMP-I18NCTX-007: writes lang and ltr direction onto the html element', () => {
withLanguage('de');
render(<TranslationProvider><Probe tKey="common.save" /></TranslationProvider>);
expect(document.documentElement.lang).toBe('de');
expect(document.documentElement.dir).toBe('ltr');
});
it('FE-COMP-I18NCTX-008: switches the html element to rtl for Arabic', async () => {
withLanguage('ar');
render(<TranslationProvider><Probe tKey="common.save" /></TranslationProvider>);
expect(document.documentElement.lang).toBe('ar');
expect(document.documentElement.dir).toBe('rtl');
await waitFor(() => expect(screen.getByTestId('value').textContent).not.toBe('Save'));
});
it('FE-COMP-I18NCTX-009: keeps the English table for an unknown language code', () => {
withLanguage('klingon');
render(<TranslationProvider><Probe tKey="common.save" /></TranslationProvider>);
expect(screen.getByTestId('value').textContent).toBe('Save');
expect(screen.getByTestId('language').textContent).toBe('klingon');
});
it('FE-COMP-I18NCTX-010: treats an empty language setting as English', () => {
withLanguage('');
render(<TranslationProvider><Probe tKey="common.save" /></TranslationProvider>);
expect(screen.getByTestId('language').textContent).toBe('en');
});
it('FE-COMP-I18NCTX-011: a locale arriving after a second switch does not win', async () => {
withLanguage('de');
render(<TranslationProvider><Probe tKey="common.save" /></TranslationProvider>);
// Switch back before the German chunk lands — the cancelled loader must not
// overwrite the English table when its promise finally resolves.
act(() => withLanguage('en'));
await act(async () => { await Promise.resolve(); });
expect(screen.getByTestId('language').textContent).toBe('en');
expect(screen.getByTestId('value').textContent).toBe('Save');
});
it('FE-COMP-I18NCTX-011a: every supported language resolves through its own chunk', async () => {
for (const { value } of SUPPORTED_LANGUAGES) {
withLanguage(value);
const view = render(<TranslationProvider><Probe tKey="common.save" /></TranslationProvider>);
await act(async () => { await Promise.resolve(); });
expect(screen.getByTestId('language').textContent).toBe(value);
// Whatever the locale ships, the key must resolve to something other than itself.
expect(screen.getByTestId('value').textContent).not.toBe('common.save');
view.unmount();
}
});
it('FE-COMP-I18NCTX-012: the default context outside a provider echoes the key', () => {
render(<Probe tKey="common.save" />);
expect(screen.getByTestId('value').textContent).toBe('common.save');
expect(screen.getByTestId('locale').textContent).toBe('en-US');
});
});
describe('tHtml', () => {
it('FE-COMP-I18NCTX-013: escapes an interpolated value before substitution', () => {
render(
<TranslationProvider>
<HtmlProbe tKey="journey.frontpage.suggestionText" params={{ title: '<img src=x onerror=alert(1)>' }} />
</TranslationProvider>,
);
const raw = screen.getByTestId('raw').textContent ?? '';
expect(raw).not.toContain('<img');
expect(raw).toContain('&lt;img');
});
it('FE-COMP-I18NCTX-014: returns the key unchanged when it is unknown', () => {
render(<TranslationProvider><HtmlProbe tKey="nope.nope" /></TranslationProvider>);
expect(screen.getByTestId('raw').textContent).toBe('nope.nope');
});
});
describe('TransHtml', () => {
it('FE-COMP-I18NCTX-015: renders as a span by default and keeps allowed inline markup', () => {
const { container } = render(
<TranslationProvider>
<TransHtml html="journey.frontpage.suggestionText" params={{ title: 'Japan 2026' }} />
</TranslationProvider>,
);
const el = container.firstElementChild!;
expect(el.tagName).toBe('SPAN');
expect(el.textContent).toContain('Japan 2026');
expect(el.querySelector('script')).toBeNull();
});
it('FE-COMP-I18NCTX-016: honours the as, className and id props', () => {
const { container } = render(
<TranslationProvider>
<TransHtml as="p" className="text-body" id="banner" html="common.save" />
</TranslationProvider>,
);
const el = container.firstElementChild!;
expect(el.tagName).toBe('P');
expect(el).toHaveClass('text-body');
expect(el.id).toBe('banner');
});
it('FE-COMP-I18NCTX-017: neutralises a script tag smuggled in through a param', () => {
const { container } = render(
<TranslationProvider>
<TransHtml html="journey.frontpage.suggestionText" params={{ title: '<script>alert(1)</script>' }} />
</TranslationProvider>,
);
expect(container.querySelector('script')).toBeNull();
expect(container.textContent).toContain('alert(1)');
});
});
@@ -160,4 +160,118 @@ describe('remoteEventHandler > assignments', () => {
expect(item1?.order_index).toBe(1);
expect(item2?.order_index).toBe(2);
});
// A collaborator can touch a day this client has never populated (the day row
// exists, but no assignments key). Every applier must fall back to an empty list.
describe('days with no assignments entry yet', () => {
it('FE-WSEVT-ASSIGN-008: assignment:created seeds a fresh day key', () => {
useTripStore.setState({ days: [buildDay({ id: 30 })], assignments: {} });
useTripStore.getState().handleRemoteEvent({
type: 'assignment:created',
assignment: buildAssignment({ id: 300, day_id: 30 }),
});
expect(useTripStore.getState().assignments['30'].map(a => a.id)).toEqual([300]);
});
it('FE-WSEVT-ASSIGN-009: assignment:updated on an unseen day yields an empty list', () => {
useTripStore.setState({ days: [buildDay({ id: 30 })], assignments: {} });
useTripStore.getState().handleRemoteEvent({
type: 'assignment:updated',
assignment: buildAssignment({ id: 300, day_id: 30 }),
});
expect(useTripStore.getState().assignments['30']).toEqual([]);
});
it('FE-WSEVT-ASSIGN-010: assignment:deleted on an unseen day yields an empty list', () => {
useTripStore.setState({ days: [buildDay({ id: 30 })], assignments: {} });
useTripStore.getState().handleRemoteEvent({ type: 'assignment:deleted', assignmentId: 1, dayId: 30 });
expect(useTripStore.getState().assignments['30']).toEqual([]);
});
it('FE-WSEVT-ASSIGN-011: assignment:reordered on an unseen day yields an empty list', () => {
useTripStore.setState({ days: [buildDay({ id: 30 })], assignments: {} });
useTripStore.getState().handleRemoteEvent({ type: 'assignment:reordered', dayId: 30, orderedIds: [1] });
expect(useTripStore.getState().assignments['30']).toEqual([]);
});
it('FE-WSEVT-ASSIGN-011b: assignment:moved between two unseen days seeds both keys', () => {
const moved = buildAssignment({ id: 300, day_id: 40 });
useTripStore.setState({ days: [buildDay({ id: 30 }), buildDay({ id: 40 })], assignments: {} });
useTripStore.getState().handleRemoteEvent({
type: 'assignment:moved',
assignment: moved,
oldDayId: 30,
newDayId: 40,
});
const { assignments } = useTripStore.getState();
expect(assignments['30']).toEqual([]);
expect(assignments['40'].map(a => a.id)).toEqual([300]);
});
it('FE-WSEVT-ASSIGN-012: an event for a day that is not in the store leaves days untouched', () => {
// The Dexie write-through resolves the Day row from Zustand; a missing row
// must not blow up the (fire-and-forget) persist.
useTripStore.setState({ days: [], assignments: {} });
expect(() => useTripStore.getState().handleRemoteEvent({
type: 'assignment:created',
assignment: buildAssignment({ id: 300, day_id: 77 }),
})).not.toThrow();
expect(useTripStore.getState().days).toEqual([]);
});
});
it('FE-WSEVT-ASSIGN-013: assignment:updated only merges into the addressed assignment', () => {
useTripStore.setState({
days: [buildDay({ id: 10 })],
assignments: {
'10': [buildAssignment({ id: 100, day_id: 10, notes: 'keep' }), buildAssignment({ id: 101, day_id: 10, notes: 'keep too' })],
},
});
useTripStore.getState().handleRemoteEvent({
type: 'assignment:updated',
assignment: buildAssignment({ id: 101, day_id: 10, notes: 'changed' }),
});
const items = useTripStore.getState().assignments['10'];
expect(items[0].notes).toBe('keep');
expect(items[1].notes).toBe('changed');
});
it('FE-WSEVT-ASSIGN-014: assignment:moved drops a stale copy already sitting on the target day', () => {
const moved = buildAssignment({ id: 100, day_id: 20 });
useTripStore.setState({
days: [buildDay({ id: 10 }), buildDay({ id: 20 })],
assignments: {
'10': [moved],
// The target day still holds the previous copy plus an unrelated item.
'20': [buildAssignment({ id: 100, day_id: 20 }), buildAssignment({ id: 200, day_id: 20 })],
},
});
useTripStore.getState().handleRemoteEvent({
type: 'assignment:moved',
assignment: moved,
oldDayId: 10,
newDayId: 20,
});
const target = useTripStore.getState().assignments['20'];
expect(target.map(a => a.id)).toEqual([200, 100]);
expect(useTripStore.getState().assignments['10']).toHaveLength(0);
});
it('FE-WSEVT-ASSIGN-015: assignment:reordered drops ids that are no longer on the day', () => {
useTripStore.setState({
days: [buildDay({ id: 10 })],
assignments: { '10': [buildAssignment({ id: 1, day_id: 10 }), buildAssignment({ id: 2, day_id: 10 })] },
});
useTripStore.getState().handleRemoteEvent({ type: 'assignment:reordered', dayId: 10, orderedIds: [2, 999, 1] });
expect(useTripStore.getState().assignments['10'].map(a => a.id)).toEqual([2, 1]);
});
it('FE-WSEVT-ASSIGN-016: assignment:reordered without orderedIds empties the day list', () => {
useTripStore.setState({
days: [buildDay({ id: 10 })],
assignments: { '10': [buildAssignment({ id: 1, day_id: 10 })] },
});
useTripStore.getState().handleRemoteEvent({ type: 'assignment:reordered', dayId: 10 });
expect(useTripStore.getState().assignments['10']).toEqual([]);
});
});
@@ -90,4 +90,112 @@ describe('remoteEventHandler > budget', () => {
const item2 = budgetItems.find(i => i.id === 2);
expect(item2?.members?.[0].paid).toBe(1);
});
it('FE-WSEVT-BUDGET-007: budget:members-updated for an unknown item leaves every item untouched', () => {
seedData();
useTripStore.getState().handleRemoteEvent({
type: 'budget:members-updated',
itemId: 4242,
members: [{ user_id: 9, paid: 0, username: 'ivan' }],
persons: 9,
});
const { budgetItems } = useTripStore.getState();
expect(budgetItems.map(i => i.persons)).toEqual([1, 2]);
expect(budgetItems[0].members).toEqual([{ ...member1 }]);
});
it('FE-WSEVT-BUDGET-008: budget:member-paid-updated only touches the addressed member', () => {
useTripStore.setState({
budgetItems: [
buildBudgetItem({ id: 1, members: [{ ...member1 }, { ...member2 }] }),
],
});
useTripStore.getState().handleRemoteEvent({
type: 'budget:member-paid-updated',
itemId: 1,
userId: 5,
paid: 1,
});
const members = useTripStore.getState().budgetItems[0].members ?? [];
expect(members.find(m => m.user_id === 5)?.paid).toBe(1);
expect(members.find(m => m.user_id === 6)?.paid).toBe(1); // seeded value, untouched
});
it('FE-WSEVT-BUDGET-009: budget:member-paid-updated on an item without members does not throw', () => {
useTripStore.setState({
budgetItems: [buildBudgetItem({ id: 1, members: undefined })],
});
useTripStore.getState().handleRemoteEvent({
type: 'budget:member-paid-updated',
itemId: 1,
userId: 5,
paid: 1,
});
expect(useTripStore.getState().budgetItems[0].members).toEqual([]);
});
describe('budget:reordered', () => {
it('FE-WSEVT-BUDGET-010: orderedIds rewrites sort_order and keeps unlisted items at the end', () => {
useTripStore.setState({
budgetItems: [
buildBudgetItem({ id: 1, sort_order: 0 }),
buildBudgetItem({ id: 2, sort_order: 1 }),
buildBudgetItem({ id: 3, sort_order: 2 }),
],
});
useTripStore.getState().handleRemoteEvent({ type: 'budget:reordered', orderedIds: [3, 1] });
const { budgetItems } = useTripStore.getState();
expect(budgetItems.map(i => i.id)).toEqual([3, 1, 2]);
// Only the listed ids get a fresh sort_order; the unlisted item keeps its own.
expect(budgetItems.map(i => i.sort_order)).toEqual([0, 1, 1]);
});
it('FE-WSEVT-BUDGET-011: an orderedIds entry for an unknown item is dropped', () => {
useTripStore.setState({
budgetItems: [buildBudgetItem({ id: 1 }), buildBudgetItem({ id: 2 })],
});
useTripStore.getState().handleRemoteEvent({ type: 'budget:reordered', orderedIds: [2, 999, 1] });
expect(useTripStore.getState().budgetItems.map(i => i.id)).toEqual([2, 1]);
});
it('FE-WSEVT-BUDGET-012: orderedCategories groups items and appends unlisted categories', () => {
useTripStore.setState({
budgetItems: [
buildBudgetItem({ id: 1, category: 'Food' }),
buildBudgetItem({ id: 2, category: 'Transport' }),
buildBudgetItem({ id: 3, category: 'Food' }),
buildBudgetItem({ id: 4, category: 'Lodging' }),
],
});
useTripStore.getState().handleRemoteEvent({
type: 'budget:reordered',
orderedCategories: ['Transport', 'Food', 'Souvenirs'],
});
// Transport, then both Food rows in their original order, then the
// category the server did not mention.
expect(useTripStore.getState().budgetItems.map(i => i.id)).toEqual([2, 1, 3, 4]);
});
it('FE-WSEVT-BUDGET-013: an item without a category is grouped under "Other"', () => {
useTripStore.setState({
budgetItems: [
buildBudgetItem({ id: 1, category: null }),
buildBudgetItem({ id: 2, category: 'Food' }),
],
});
useTripStore.getState().handleRemoteEvent({
type: 'budget:reordered',
orderedCategories: ['Other', 'Food'],
});
expect(useTripStore.getState().budgetItems.map(i => i.id)).toEqual([1, 2]);
});
it('FE-WSEVT-BUDGET-014: a payload with neither key is a no-op', () => {
useTripStore.setState({
budgetItems: [buildBudgetItem({ id: 1 }), buildBudgetItem({ id: 2 })],
});
useTripStore.getState().handleRemoteEvent({ type: 'budget:reordered' });
expect(useTripStore.getState().budgetItems.map(i => i.id)).toEqual([1, 2]);
});
});
});
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { useTripStore } from '../../../src/store/tripStore';
import { resetAllStores } from '../../helpers/store';
import { buildDayNote } from '../../helpers/factories';
import { buildDay, buildDayNote } from '../../helpers/factories';
beforeEach(() => {
resetAllStores();
@@ -50,6 +50,52 @@ describe('remoteEventHandler > dayNotes', () => {
expect(dayNotes['10']).toHaveLength(0);
});
it('FE-WSEVT-DAYNOTE-006: dayNote:updated only replaces the addressed note', () => {
useTripStore.setState({
days: [buildDay({ id: 10 })],
dayNotes: { '10': [buildDayNote({ id: 1, day_id: 10, text: 'keep' }), buildDayNote({ id: 2, day_id: 10, text: 'old' })] },
});
useTripStore.getState().handleRemoteEvent({
type: 'dayNote:updated',
dayId: 10,
note: buildDayNote({ id: 2, day_id: 10, text: 'new' }),
});
expect(useTripStore.getState().dayNotes['10'].map(n => n.text)).toEqual(['keep', 'new']);
});
// A collaborator can add the first note to a day this client never populated.
describe('days with no dayNotes entry yet', () => {
const seedBareDay = () => {
useTripStore.setState({ days: [buildDay({ id: 30 })], dayNotes: {} });
};
it('FE-WSEVT-DAYNOTE-007: dayNote:created seeds a fresh day key', () => {
seedBareDay();
useTripStore.getState().handleRemoteEvent({
type: 'dayNote:created',
dayId: 30,
note: buildDayNote({ id: 9, day_id: 30 }),
});
expect(useTripStore.getState().dayNotes['30'].map(n => n.id)).toEqual([9]);
});
it('FE-WSEVT-DAYNOTE-008: dayNote:updated on an unseen day yields an empty list', () => {
seedBareDay();
useTripStore.getState().handleRemoteEvent({
type: 'dayNote:updated',
dayId: 30,
note: buildDayNote({ id: 9, day_id: 30 }),
});
expect(useTripStore.getState().dayNotes['30']).toEqual([]);
});
it('FE-WSEVT-DAYNOTE-009: dayNote:deleted on an unseen day yields an empty list', () => {
seedBareDay();
useTripStore.getState().handleRemoteEvent({ type: 'dayNote:deleted', dayId: 30, noteId: 9 });
expect(useTripStore.getState().dayNotes['30']).toEqual([]);
});
});
it('FE-WSEVT-DAYNOTE-005: operations on day 10 do not affect day 20', () => {
seedData();
const newNote = buildDayNote({ id: 50, day_id: 10, text: 'Day 10 note' });
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { useTripStore } from '../../../src/store/tripStore';
import { resetAllStores } from '../../helpers/store';
import { buildDay, buildAssignment, buildDayNote } from '../../helpers/factories';
import { buildDay, buildAssignment, buildDayNote, buildTrip } from '../../helpers/factories';
beforeEach(() => {
resetAllStores();
@@ -77,4 +77,72 @@ describe('remoteEventHandler > days', () => {
expect('20' in assignments).toBe(true);
expect('20' in dayNotes).toBe(true);
});
// The reorder is applied optimistically from orderedIds, then the authoritative
// dates + re-stamped booking times are pulled (#589).
describe('day:reordered', () => {
const stubRefresh = () => {
const refreshDays = vi.fn(async () => {});
const loadReservations = vi.fn(async () => {});
useTripStore.setState({ refreshDays, loadReservations });
return { refreshDays, loadReservations };
};
const seedThreeDays = () => {
useTripStore.setState({
trip: buildTrip({ id: 7 }),
days: [
buildDay({ id: 10, day_number: 1 }),
buildDay({ id: 20, day_number: 2 }),
buildDay({ id: 30, day_number: 3 }),
],
});
};
it('FE-WSEVT-DAY-008: applies the new order and renumbers day_number', () => {
seedThreeDays();
stubRefresh();
useTripStore.getState().handleRemoteEvent({ type: 'day:reordered', orderedIds: [30, 10, 20] });
const { days } = useTripStore.getState();
expect(days.map(d => d.id)).toEqual([30, 10, 20]);
expect(days.map(d => d.day_number)).toEqual([1, 2, 3]);
});
it('FE-WSEVT-DAY-009: pulls the authoritative days + reservations after a reorder', () => {
seedThreeDays();
const { refreshDays, loadReservations } = stubRefresh();
useTripStore.getState().handleRemoteEvent({ type: 'day:reordered', orderedIds: [30, 10, 20] });
expect(refreshDays).toHaveBeenCalledWith(7);
expect(loadReservations).toHaveBeenCalledWith(7);
});
it('FE-WSEVT-DAY-010: a partial orderedIds list leaves the order untouched', () => {
seedThreeDays();
stubRefresh();
useTripStore.getState().handleRemoteEvent({ type: 'day:reordered', orderedIds: [30, 10] });
expect(useTripStore.getState().days.map(d => d.id)).toEqual([10, 20, 30]);
});
it('FE-WSEVT-DAY-011: an unknown day id leaves the order untouched', () => {
seedThreeDays();
stubRefresh();
useTripStore.getState().handleRemoteEvent({ type: 'day:reordered', orderedIds: [30, 10, 999] });
expect(useTripStore.getState().days.map(d => d.id)).toEqual([10, 20, 30]);
});
it('FE-WSEVT-DAY-012: a missing orderedIds payload is a no-op', () => {
seedThreeDays();
stubRefresh();
useTripStore.getState().handleRemoteEvent({ type: 'day:reordered' });
expect(useTripStore.getState().days.map(d => d.id)).toEqual([10, 20, 30]);
});
it('FE-WSEVT-DAY-013: without a loaded trip nothing is refetched', () => {
useTripStore.setState({ trip: null, days: [buildDay({ id: 10 }), buildDay({ id: 20 })] });
const { refreshDays, loadReservations } = stubRefresh();
useTripStore.getState().handleRemoteEvent({ type: 'day:reordered', orderedIds: [20, 10] });
expect(refreshDays).not.toHaveBeenCalled();
expect(loadReservations).not.toHaveBeenCalled();
});
});
});
@@ -47,6 +47,17 @@ describe('remoteEventHandler > files', () => {
expect(files).toHaveLength(0);
});
it('FE-WSEVT-FILE-006: file:updated leaves the other files untouched', () => {
useTripStore.setState({
files: [buildTripFile({ id: 1, original_name: 'a.pdf' }), buildTripFile({ id: 2, original_name: 'b.pdf' })],
});
useTripStore.getState().handleRemoteEvent({
type: 'file:updated',
file: buildTripFile({ id: 2, original_name: 'b-renamed.pdf' }),
});
expect(useTripStore.getState().files.map(f => f.original_name)).toEqual(['a.pdf', 'b-renamed.pdf']);
});
it('FE-WSEVT-FILE-005: file:created ordering — newest is first', () => {
seedData();
const f2 = buildTripFile({ id: 2, original_name: 'second.pdf' });
@@ -46,4 +46,15 @@ describe('remoteEventHandler > packing', () => {
const { packingItems } = useTripStore.getState();
expect(packingItems).toHaveLength(0);
});
it('FE-WSEVT-PACK-005: packing:updated leaves the other items untouched', () => {
useTripStore.setState({
packingItems: [buildPackingItem({ id: 1, name: 'Sunscreen' }), buildPackingItem({ id: 2, name: 'Hat' })],
});
useTripStore.getState().handleRemoteEvent({
type: 'packing:updated',
item: buildPackingItem({ id: 2, name: 'Sun hat' }),
});
expect(useTripStore.getState().packingItems.map(i => i.name)).toEqual(['Sunscreen', 'Sun hat']);
});
});
@@ -64,4 +64,40 @@ describe('remoteEventHandler > places', () => {
const { assignments } = useTripStore.getState();
expect(assignments['10']).toHaveLength(0);
});
it('FE-WSEVT-PLACE-007: place:updated leaves other places and their assignments untouched', () => {
const one = buildPlace({ id: 1, name: 'One' });
const two = buildPlace({ id: 2, name: 'Two' });
useTripStore.setState({
places: [one, two],
assignments: {
'10': [
buildAssignment({ id: 100, place: one, day_id: 10 }),
buildAssignment({ id: 200, place: two, day_id: 10 }),
],
},
});
useTripStore.getState().handleRemoteEvent({ type: 'place:updated', place: buildPlace({ id: 2, name: 'Two renamed' }) });
const { places, assignments } = useTripStore.getState();
expect(places.map(p => p.name)).toEqual(['One', 'Two renamed']);
expect(assignments['10'].map(a => a.place?.name)).toEqual(['One', 'Two renamed']);
});
it('FE-WSEVT-PLACE-008: place:deleted keeps assignments of the other places', () => {
const one = buildPlace({ id: 1 });
const two = buildPlace({ id: 2 });
useTripStore.setState({
places: [one, two],
assignments: {
'10': [
buildAssignment({ id: 100, place: one, day_id: 10 }),
buildAssignment({ id: 200, place: two, day_id: 10 }),
],
},
});
useTripStore.getState().handleRemoteEvent({ type: 'place:deleted', placeId: 1 });
const { places, assignments } = useTripStore.getState();
expect(places.map(p => p.id)).toEqual([2]);
expect(assignments['10'].map(a => a.id)).toEqual([200]);
});
});
@@ -1,7 +1,10 @@
import { describe, it, expect } from 'vitest';
import { describe, it, expect, beforeEach } from 'vitest';
import { TREK_WS_EVENT_NAMES, TREK_WS_TRIP_EVENT_NAMES } from '@trek/shared';
import { DEXIE_WRITERS, STATE_APPLIERS } from '../../../src/store/slices/remoteEventHandler';
import { HANDLED_OUTSIDE_TRIP_STORE, IGNORED_WS_EVENTS } from '../../../src/api/wsEventPolicy';
import { useTripStore } from '../../../src/store/tripStore';
import { resetAllStores } from '../../helpers/store';
import { buildPackingItem, buildPlace } from '../../helpers/factories';
/**
* The exhaustiveness ratchet (roadmap: WS event contract registry). Every
@@ -18,6 +21,10 @@ const handledInStore = new Set<string>([
const handledElsewhere = new Set<string>(HANDLED_OUTSIDE_TRIP_STORE);
const ignored = new Set<string>(IGNORED_WS_EVENTS);
beforeEach(() => {
resetAllStores();
});
describe('remoteEventHandler > registry parity', () => {
it('FE-WSEVT-REGISTRY-001: every registry event is handled or explicitly ignored', () => {
const unclassified = TREK_WS_EVENT_NAMES.filter(
@@ -65,4 +72,21 @@ describe('remoteEventHandler > registry parity', () => {
);
expect(writersWithoutApplier).toEqual([]);
});
it('FE-WSEVT-REGISTRY-006: an explicitly ignored event leaves the store untouched', () => {
const items = [buildPackingItem({ id: 1 }), buildPackingItem({ id: 2 })];
useTripStore.setState({ packingItems: items, places: [buildPlace({ id: 5 })] });
// 'packing:reordered' is on IGNORED_WS_EVENTS — the reducer must swallow it
// instead of throwing or clearing the slice.
useTripStore.getState().handleRemoteEvent({ type: 'packing:reordered', orderedIds: [2, 1] });
const state = useTripStore.getState();
expect(state.packingItems.map(i => i.id)).toEqual([1, 2]);
expect(state.places.map(p => p.id)).toEqual([5]);
});
it('FE-WSEVT-REGISTRY-007: an unknown event name is a no-op', () => {
useTripStore.setState({ places: [buildPlace({ id: 5 })] });
useTripStore.getState().handleRemoteEvent({ type: 'not:a:real:event', payload: 1 });
expect(useTripStore.getState().places.map(p => p.id)).toEqual([5]);
});
});
@@ -58,4 +58,43 @@ describe('remoteEventHandler > reservations', () => {
expect(reservations[1].id).toBe(2);
expect(reservations[2].id).toBe(1);
});
it('FE-WSEVT-RESERV-006: reservation:updated leaves the other reservations untouched', () => {
useTripStore.setState({
reservations: [buildReservation({ id: 1, title: 'Hotel' }), buildReservation({ id: 2, title: 'Flight' })],
});
useTripStore.getState().handleRemoteEvent({
type: 'reservation:updated',
reservation: buildReservation({ id: 2, title: 'Flight (rebooked)' }),
});
const { reservations } = useTripStore.getState();
expect(reservations[0].title).toBe('Hotel');
expect(reservations[1].title).toBe('Flight (rebooked)');
});
// Traveler assignment (#1517) arrives as its own event carrying only the list.
it('FE-WSEVT-RESERV-007: reservation:travelers-updated replaces travelers on the addressed booking', () => {
useTripStore.setState({
reservations: [buildReservation({ id: 1 }), buildReservation({ id: 2 })],
});
const travelers = [{ user_id: 3, username: 'ada' }, { user_id: 4, username: 'grace' }];
useTripStore.getState().handleRemoteEvent({
type: 'reservation:travelers-updated',
reservationId: 2,
travelers,
});
const { reservations } = useTripStore.getState();
expect(reservations[1].travelers).toEqual(travelers);
expect(reservations[0].travelers).toBeUndefined();
});
it('FE-WSEVT-RESERV-008: reservation:travelers-updated for an unknown booking changes nothing', () => {
useTripStore.setState({ reservations: [buildReservation({ id: 1 })] });
useTripStore.getState().handleRemoteEvent({
type: 'reservation:travelers-updated',
reservationId: 999,
travelers: [{ user_id: 3, username: 'ada' }],
});
expect(useTripStore.getState().reservations[0].travelers).toBeUndefined();
});
});
@@ -46,4 +46,15 @@ describe('remoteEventHandler > todo', () => {
const { todoItems } = useTripStore.getState();
expect(todoItems).toHaveLength(0);
});
it('FE-WSEVT-TODO-005: todo:updated leaves the other items untouched', () => {
useTripStore.setState({
todoItems: [buildTodoItem({ id: 1, name: 'Book flights' }), buildTodoItem({ id: 2, name: 'Renew passport' })],
});
useTripStore.getState().handleRemoteEvent({
type: 'todo:updated',
item: buildTodoItem({ id: 2, name: 'Renew passport (done)' }),
});
expect(useTripStore.getState().todoItems.map(i => i.name)).toEqual(['Book flights', 'Renew passport (done)']);
});
});
@@ -239,6 +239,20 @@ describe('onPhotoLoaded', () => {
expect(fn).toHaveBeenCalledWith(expect.objectContaining({ photoUrl: 'https://example.com/photo.jpg' }));
});
it('FE-COMP-PHOTO-023: several listeners on the same key all fire', async () => {
mockPlacePhoto.mockResolvedValue({ photoUrl: 'https://example.com/photo.jpg' });
const first = vi.fn();
const second = vi.fn();
svc.onPhotoLoaded('k', first);
svc.onPhotoLoaded('k', second);
svc.fetchPhoto('k', 'pid');
await flush();
expect(first).toHaveBeenCalledTimes(1);
expect(second).toHaveBeenCalledTimes(1);
});
it('FE-COMP-PHOTO-011: unsubscribe prevents callback from being called', async () => {
mockPlacePhoto.mockResolvedValue({ photoUrl: 'https://example.com/photo.jpg' });
@@ -274,6 +288,40 @@ describe('onThumbReady', () => {
expect(svc.getCached('k')?.thumbDataUrl).toBe('data:image/webp;base64,thumb');
});
it('FE-COMP-PHOTO-024: several thumb listeners on the same key all fire', async () => {
mockPlacePhoto.mockResolvedValue({ photoUrl: 'https://example.com/img.jpg' });
setupImageAutoLoad(true);
vi.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockReturnValue('data:image/webp;base64,thumb');
const first = vi.fn();
const second = vi.fn();
svc.onThumbReady('k', first);
svc.onThumbReady('k', second);
svc.fetchPhoto('k', 'pid');
await flush();
await flush();
expect(first).toHaveBeenCalledWith('data:image/webp;base64,thumb');
expect(second).toHaveBeenCalledWith('data:image/webp;base64,thumb');
});
it('FE-COMP-PHOTO-025: no thumb notification when the conversion fails', async () => {
mockPlacePhoto.mockResolvedValue({ photoUrl: 'https://example.com/img.jpg' });
setupImageAutoLoad(false); // img.onerror → urlToBase64 resolves null
const fn = vi.fn();
svc.onThumbReady('k', fn);
svc.fetchPhoto('k', 'pid');
await flush();
await flush();
expect(fn).not.toHaveBeenCalled();
expect(svc.getCached('k')?.photoUrl).toBe('https://example.com/img.jpg');
expect(svc.getCached('k')?.thumbDataUrl).toBeNull();
});
it('FE-COMP-PHOTO-013: unsubscribe prevents thumb callback', async () => {
mockPlacePhoto.mockResolvedValue({ photoUrl: 'https://example.com/img.jpg' });
setupImageAutoLoad(true);
@@ -313,6 +361,99 @@ describe('urlToBase64', () => {
setupImageAutoLoad(true);
await expect(svc.urlToBase64('https://example.com/img.jpg')).resolves.not.toThrow();
});
it('FE-COMP-PHOTO-022: returns null when the 2d context is unavailable', async () => {
setupImageAutoLoad(true);
// jsdom-style environment without canvas support: getContext yields null and
// the first drawing call throws — the conversion must degrade to null.
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
await expect(svc.urlToBase64('https://example.com/img.jpg')).resolves.toBeNull();
});
});
// ==============================================================================
// fetchPhoto — stable proxy URL shortcut
// ==============================================================================
describe('fetchPhoto — stable proxy URL', () => {
it('FE-COMP-PHOTO-018: uses the proxy URL directly and skips the API round-trip', async () => {
vi.spyOn(HTMLCanvasElement.prototype, 'toDataURL').mockReturnValue('data:image/webp;base64,proxy');
const cb = vi.fn();
const thumbFn = vi.fn();
svc.onThumbReady('k', thumbFn);
svc.fetchPhoto('k', '/api/maps/place-photo/abc123', undefined, undefined, undefined, cb);
// Synchronous — no request slot, no API call.
expect(mockPlacePhoto).not.toHaveBeenCalled();
expect(cb).toHaveBeenCalledWith({ photoUrl: '/api/maps/place-photo/abc123', thumbDataUrl: null });
await flush();
await flush();
expect(thumbFn).toHaveBeenCalledWith('data:image/webp;base64,proxy');
expect(svc.getCached('k')?.thumbDataUrl).toBe('data:image/webp;base64,proxy');
});
it('FE-COMP-PHOTO-019: a failing thumb conversion leaves the proxy entry without a thumb', async () => {
setupImageAutoLoad(false); // img.onerror → urlToBase64 resolves null
const thumbFn = vi.fn();
svc.onThumbReady('k', thumbFn);
svc.fetchPhoto('k', '/api/maps/place-photo/abc123');
await flush();
await flush();
expect(thumbFn).not.toHaveBeenCalled();
expect(svc.getCached('k')).toEqual({ photoUrl: '/api/maps/place-photo/abc123', thumbDataUrl: null });
});
it('FE-COMP-PHOTO-020: a listener registered while a fetch is in flight still receives the entry', async () => {
let resolve!: (v: { photoUrl: string }) => void;
mockPlacePhoto.mockReturnValue(new Promise<{ photoUrl: string }>(r => { resolve = r; }));
svc.fetchPhoto('k', 'pid');
await flush();
expect(svc.isLoading('k')).toBe(true);
// Further calls while in flight are deduplicated, with or without a callback.
svc.fetchPhoto('k', 'pid');
const late = vi.fn();
svc.fetchPhoto('k', 'pid', undefined, undefined, undefined, late);
expect(mockPlacePhoto).toHaveBeenCalledTimes(1);
resolve({ photoUrl: 'https://example.com/photo.jpg' });
await flush();
expect(late).toHaveBeenCalledWith(expect.objectContaining({ photoUrl: 'https://example.com/photo.jpg' }));
});
});
// ==============================================================================
// fetchPhoto — concurrency limiter
// ==============================================================================
describe('fetchPhoto — concurrency limiter', () => {
it('FE-COMP-PHOTO-021: at most 5 requests run at once; the 6th starts when one finishes', async () => {
const resolvers: Array<(v: { photoUrl: string }) => void> = [];
mockPlacePhoto.mockImplementation(() =>
new Promise<{ photoUrl: string }>(r => { resolvers.push(r); }));
for (let i = 0; i < 6; i += 1) {
svc.fetchPhoto(`k${i}`, `pid${i}`);
}
await flush();
expect(mockPlacePhoto).toHaveBeenCalledTimes(5);
// Freeing one slot lets the queued request through.
resolvers[0]({ photoUrl: 'https://example.com/0.jpg' });
await flush();
expect(mockPlacePhoto).toHaveBeenCalledTimes(6);
});
});
// ==============================================================================
@@ -98,6 +98,101 @@ describe('assignmentsSlice', () => {
const result = await useTripStore.getState().assignPlaceToDay(1, 1, 999);
expect(result).toBeUndefined();
});
it('FE-ASSIGN-008: a day with no assignments entry yet is seeded from scratch', async () => {
const place = buildPlace({ id: 10, trip_id: 1 });
seedStore(useTripStore, { places: [place], assignments: {} });
server.use(
http.post('/api/trips/1/days/1/assignments', () =>
HttpResponse.json({ assignment: buildAssignment({ id: 999, day_id: 1, place_id: 10, place }) })
),
);
await useTripStore.getState().assignPlaceToDay(1, 1, 10);
expect(useTripStore.getState().assignments['1'].map(a => a.id)).toEqual([999]);
});
it('FE-ASSIGN-009: a response without a nested place falls back to the store place', async () => {
const place = buildPlace({ id: 10, trip_id: 1, name: 'Louvre' });
seedStore(useTripStore, { places: [place], assignments: { '1': [] } });
const bare = { ...buildAssignment({ id: 999, day_id: 1, place_id: 10 }), place: undefined };
server.use(
http.post('/api/trips/1/days/1/assignments', () => HttpResponse.json({ assignment: bare })),
);
await useTripStore.getState().assignPlaceToDay(1, 1, 10);
expect(useTripStore.getState().assignments['1'][0].place?.name).toBe('Louvre');
});
it('FE-ASSIGN-010: inserting at a position keeps the other rows and reorders server-side', async () => {
const place = buildPlace({ id: 10, trip_id: 1 });
const existing = buildAssignment({ id: 1, day_id: 1, order_index: 0 });
const other = buildAssignment({ id: 2, day_id: 1, order_index: 1 });
seedStore(useTripStore, { places: [place], assignments: { '1': [existing, other] } });
let reorderBody: number[] | undefined;
server.use(
http.post('/api/trips/1/days/1/assignments', () =>
HttpResponse.json({ assignment: buildAssignment({ id: 999, day_id: 1, place_id: 10, place, order_index: 7 }) })
),
http.put('/api/trips/1/days/1/assignments/reorder', async ({ request }) => {
const body = await request.json() as { orderedIds: number[] };
reorderBody = body.orderedIds;
return HttpResponse.json({ success: true });
}),
);
await useTripStore.getState().assignPlaceToDay(1, 1, 10, 1);
const items = useTripStore.getState().assignments['1'];
expect(items.map(a => a.id)).toEqual([1, 999, 2]);
expect(items.map(a => a.order_index)).toEqual([0, 1, 2]);
expect(reorderBody).toEqual([1, 999, 2]);
});
it('FE-ASSIGN-011: a failing follow-up reorder keeps the optimistic order', async () => {
const place = buildPlace({ id: 10, trip_id: 1 });
seedStore(useTripStore, {
places: [place],
assignments: { '1': [buildAssignment({ id: 1, day_id: 1, order_index: 0 })] },
});
server.use(
http.post('/api/trips/1/days/1/assignments', () =>
HttpResponse.json({ assignment: buildAssignment({ id: 999, day_id: 1, place_id: 10, place }) })
),
http.put('/api/trips/1/days/1/assignments/reorder', () =>
HttpResponse.json({ message: 'Error' }, { status: 500 })
),
);
// The reorder failure is swallowed — the create itself already succeeded.
await expect(useTripStore.getState().assignPlaceToDay(1, 1, 10, 0)).resolves.toBeDefined();
expect(useTripStore.getState().assignments['1'].map(a => a.id)).toEqual([999, 1]);
});
it('FE-ASSIGN-012: no reorder call when the day holds no server-side ids', async () => {
const place = buildPlace({ id: 10, trip_id: 1 });
seedStore(useTripStore, { places: [place], assignments: { '1': [] } });
let reorderCalls = 0;
server.use(
// An unsynced (still negative) id echoed back by the offline replay path.
http.post('/api/trips/1/days/1/assignments', () =>
HttpResponse.json({ assignment: buildAssignment({ id: -42, day_id: 1, place_id: 10, place }) })
),
http.put('/api/trips/1/days/1/assignments/reorder', () => {
reorderCalls += 1;
return HttpResponse.json({ success: true });
}),
);
await useTripStore.getState().assignPlaceToDay(1, 1, 10, 0);
expect(reorderCalls).toBe(0);
expect(useTripStore.getState().assignments['1'].map(a => a.id)).toEqual([-42]);
});
});
describe('removeAssignment', () => {
@@ -175,6 +270,25 @@ describe('assignmentsSlice', () => {
expect(dayAssignments.find(a => a.id === 1)?.order_index).toBe(0);
expect(dayAssignments.find(a => a.id === 2)?.order_index).toBe(1);
});
it('FE-ASSIGN-013: ids that are no longer on the day are dropped from the new order', async () => {
const a1 = buildAssignment({ id: 1, day_id: 5, order_index: 0 });
seedStore(useTripStore, { assignments: { '5': [a1] } });
await useTripStore.getState().reorderAssignments(1, 5, [999, 1]);
const dayAssignments = useTripStore.getState().assignments['5'];
expect(dayAssignments.map(a => a.id)).toEqual([1]);
expect(dayAssignments[0].order_index).toBe(1);
});
it('FE-ASSIGN-014: reordering a day with no assignments entry yields an empty list', async () => {
seedStore(useTripStore, { assignments: {} });
await useTripStore.getState().reorderAssignments(1, 5, [1, 2]);
expect(useTripStore.getState().assignments['5']).toEqual([]);
});
});
describe('moveAssignment', () => {
@@ -218,5 +332,76 @@ describe('assignmentsSlice', () => {
expect(useTripStore.getState().assignments['1'][0].id).toBe(50);
expect(useTripStore.getState().assignments['2']).toHaveLength(0);
});
it('FE-ASSIGN-015: an unknown assignment id is a no-op', async () => {
seedStore(useTripStore, { assignments: { '1': [buildAssignment({ id: 50, day_id: 1 })] } });
await useTripStore.getState().moveAssignment(1, 999, 1, 2);
expect(useTripStore.getState().assignments['1']).toHaveLength(1);
expect(useTripStore.getState().assignments['2']).toBeUndefined();
});
it('FE-ASSIGN-016: a source day with no assignments entry is a no-op', async () => {
seedStore(useTripStore, { assignments: {} });
await useTripStore.getState().moveAssignment(1, 50, 1, 2);
expect(useTripStore.getState().assignments).toEqual({});
});
it('FE-ASSIGN-017: dropping at an explicit index renumbers the target day and pushes the new order', async () => {
const moved = buildAssignment({ id: 50, day_id: 1, order_index: 0 });
const t1 = buildAssignment({ id: 60, day_id: 2, order_index: 1 });
const t2 = buildAssignment({ id: 61, day_id: 2, order_index: 0 });
seedStore(useTripStore, { assignments: { '1': [moved], '2': [t1, t2] } });
let reorderBody: number[] | undefined;
server.use(
http.put('/api/trips/1/days/2/assignments/reorder', async ({ request }) => {
const body = await request.json() as { orderedIds: number[] };
reorderBody = body.orderedIds;
return HttpResponse.json({ success: true });
}),
);
await useTripStore.getState().moveAssignment(1, 50, 1, 2, 1);
const target = useTripStore.getState().assignments['2'];
// Target day is sorted by order_index first (61, 60), then the drop lands at index 1.
expect(target.map(a => a.id)).toEqual([61, 50, 60]);
expect(target.map(a => a.order_index)).toEqual([0, 1, 2]);
expect(target[1].day_id).toBe(2);
expect(reorderBody).toEqual([61, 50, 60]);
});
it('FE-ASSIGN-018: moving onto a day with no assignments entry skips the reorder call', async () => {
const moved = buildAssignment({ id: 50, day_id: 1, order_index: 0 });
seedStore(useTripStore, { assignments: { '1': [moved] } });
let reorderCalls = 0;
server.use(
http.put('/api/trips/1/days/2/assignments/reorder', () => {
reorderCalls += 1;
return HttpResponse.json({ success: true });
}),
);
await useTripStore.getState().moveAssignment(1, 50, 1, 2);
expect(useTripStore.getState().assignments['2'].map(a => a.id)).toEqual([50]);
expect(reorderCalls).toBe(0);
});
});
describe('setAssignments', () => {
it('FE-ASSIGN-019: replaces the whole assignments map', () => {
seedStore(useTripStore, { assignments: { '1': [buildAssignment({ id: 1, day_id: 1 })] } });
const next = { '9': [buildAssignment({ id: 90, day_id: 9 })] };
useTripStore.getState().setAssignments(next);
expect(useTripStore.getState().assignments).toEqual(next);
});
});
});
+245 -1
View File
@@ -1,7 +1,8 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { http, HttpResponse } from 'msw';
import { server } from '../../helpers/msw/server';
import { useAuthStore } from '../../../src/store/authStore';
import { useSystemNoticeStore } from '../../../src/store/systemNoticeStore';
import { authApi } from '../../../src/api/client';
import { resetAllStores } from '../../helpers/store';
import { buildUser } from '../../helpers/factories';
@@ -9,9 +10,28 @@ import { buildUser } from '../../helpers/factories';
// The websocket module is already mocked globally in tests/setup.ts
import { connect, disconnect } from '../../../src/api/websocket';
// The user-scoped offline DB is real (fake-indexeddb); only the reopen step is
// made failable so the "auth still succeeds when the DB won't open" path runs.
const dbControl = vi.hoisted(() => ({ reopenFails: false }));
vi.mock('../../../src/db/offlineDb', async (importOriginal) => {
const actual = await importOriginal<typeof import('../../../src/db/offlineDb')>();
return {
...actual,
reopenForUser: async (userId: number | string) => {
if (dbControl.reopenFails) throw new Error('offline db locked');
return actual.reopenForUser(userId);
},
};
});
beforeEach(() => {
resetAllStores();
vi.clearAllMocks();
dbControl.reopenFails = false;
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('authStore', () => {
@@ -488,4 +508,228 @@ describe('authStore', () => {
expect(useAuthStore.getState().isAuthenticated).toBe(true);
});
});
describe('FE-STORE-AUTH-024: system notices are skipped for a forced password change', () => {
const stubNoticeFetch = () => {
const fetch = vi.fn(async () => {});
useSystemNoticeStore.setState({ fetch });
return fetch;
};
it('login skips the notice fetch when must_change_password is set', async () => {
const user = buildUser({ must_change_password: true });
server.use(http.post('/api/auth/login', () => HttpResponse.json({ user, token: 'tok' })));
const noticeFetch = stubNoticeFetch();
await useAuthStore.getState().login(user.email, 'password');
expect(useAuthStore.getState().isAuthenticated).toBe(true);
expect(noticeFetch).not.toHaveBeenCalled();
});
it('completeMfaLogin skips the notice fetch when must_change_password is set', async () => {
const user = buildUser({ must_change_password: true });
server.use(http.post('/api/auth/mfa/verify-login', () => HttpResponse.json({ user, token: 'tok' })));
const noticeFetch = stubNoticeFetch();
await useAuthStore.getState().completeMfaLogin('mfa-tok', '123 456');
expect(useAuthStore.getState().isAuthenticated).toBe(true);
expect(noticeFetch).not.toHaveBeenCalled();
});
});
describe('FE-STORE-AUTH-025: offline DB cannot be opened', () => {
it('login still authenticates and logs the failure', async () => {
const user = buildUser();
server.use(http.post('/api/auth/login', () => HttpResponse.json({ user, token: 'tok' })));
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
dbControl.reopenFails = true;
await useAuthStore.getState().login(user.email, 'password');
expect(useAuthStore.getState().isAuthenticated).toBe(true);
expect(consoleError).toHaveBeenCalledWith(
'[auth] failed to open user-scoped offline DB',
expect.any(Error),
);
});
});
describe('FE-STORE-AUTH-026: logout hardening', () => {
it('clears the service-worker caches and finishes even when every teardown step fails', async () => {
useAuthStore.setState({ user: buildUser(), isAuthenticated: true, authCheckFailed: true });
const cacheDelete = vi.fn(() => Promise.reject(new Error('cache api unavailable')));
Object.defineProperty(window, 'caches', {
value: { delete: cacheDelete },
configurable: true,
writable: true,
});
vi.spyOn(globalThis, 'fetch').mockRejectedValue(new Error('offline'));
await useAuthStore.getState().logout();
expect(cacheDelete).toHaveBeenCalledWith('api-data');
expect(cacheDelete).toHaveBeenCalledWith('user-uploads');
const state = useAuthStore.getState();
expect(state.user).toBeNull();
expect(state.isAuthenticated).toBe(false);
expect(state.authCheckFailed).toBe(false);
delete (window as unknown as { caches?: unknown }).caches;
});
});
describe('FE-STORE-AUTH-027: loadUser while genuinely offline', () => {
it('keeps the persisted session and does not raise authCheckFailed', async () => {
const onLine = Object.getOwnPropertyDescriptor(Navigator.prototype, 'onLine');
Object.defineProperty(navigator, 'onLine', { value: false, configurable: true });
useAuthStore.setState({ user: buildUser(), isAuthenticated: true });
// A transport-level failure carries no `response`, so status stays undefined.
vi.spyOn(authApi, 'me').mockRejectedValueOnce(new Error('Network Error'));
await useAuthStore.getState().loadUser();
const state = useAuthStore.getState();
expect(state.isAuthenticated).toBe(true);
expect(state.isLoading).toBe(false);
expect(state.authCheckFailed).toBe(false);
if (onLine) Object.defineProperty(Navigator.prototype, 'onLine', onLine);
delete (navigator as unknown as { onLine?: boolean }).onLine;
});
it('flags authCheckFailed when the server is unreachable but we are online', async () => {
useAuthStore.setState({ user: buildUser(), isAuthenticated: true });
vi.spyOn(authApi, 'me').mockRejectedValueOnce(new Error('Network Error'));
await useAuthStore.getState().loadUser();
expect(useAuthStore.getState().authCheckFailed).toBe(true);
expect(useAuthStore.getState().isAuthenticated).toBe(true);
});
});
describe('FE-STORE-AUTH-028: stale loadUser rejection', () => {
it('does not clear the session a newer login established', async () => {
let rejectStale!: (e: Error) => void;
const stale = new Promise((_, reject) => { rejectStale = reject; });
vi.spyOn(authApi, 'me').mockImplementationOnce(() => stale);
const staleLoad = useAuthStore.getState().loadUser();
const freshUser = buildUser({ username: 'freshlogin' });
server.use(http.post('/api/auth/login', () => HttpResponse.json({ user: freshUser, token: 'tok' })));
await useAuthStore.getState().login(freshUser.email, 'password');
rejectStale(Object.assign(new Error('Unauthorized'), { response: { status: 401 } }));
await staleLoad;
const state = useAuthStore.getState();
expect(state.user?.username).toBe('freshlogin');
expect(state.isAuthenticated).toBe(true);
});
});
describe('FE-STORE-AUTH-029: API-key and profile error paths', () => {
it('updateMapsKey surfaces the server message', async () => {
server.use(http.put('/api/auth/me/maps-key', () =>
HttpResponse.json({ error: 'Invalid key' }, { status: 400 })));
await expect(useAuthStore.getState().updateMapsKey('bad')).rejects.toThrow('Invalid key');
});
it('updateMapsKey without a signed-in user leaves user null', async () => {
server.use(http.put('/api/auth/me/maps-key', () => HttpResponse.json({ success: true })));
useAuthStore.setState({ user: null, hasMapsKey: false });
await useAuthStore.getState().updateMapsKey('a-key');
expect(useAuthStore.getState().user).toBeNull();
expect(useAuthStore.getState().hasMapsKey).toBe(true);
});
it('updateApiKeys mirrors a maps_api_key into hasMapsKey', async () => {
const updatedUser = buildUser();
server.use(http.put('/api/auth/me/api-keys', () => HttpResponse.json({ user: updatedUser })));
await useAuthStore.getState().updateApiKeys({ maps_api_key: 'k' });
expect(useAuthStore.getState().hasMapsKey).toBe(true);
await useAuthStore.getState().updateApiKeys({ maps_api_key: null });
expect(useAuthStore.getState().hasMapsKey).toBe(false);
});
it('updateApiKeys surfaces the server message', async () => {
server.use(http.put('/api/auth/me/api-keys', () =>
HttpResponse.json({ error: 'Rejected' }, { status: 400 })));
await expect(useAuthStore.getState().updateApiKeys({ some_key: 'v' })).rejects.toThrow('Rejected');
});
it('updateProfile surfaces the server message', async () => {
server.use(http.put('/api/auth/me/settings', () =>
HttpResponse.json({ error: 'Username taken' }, { status: 409 })));
await expect(useAuthStore.getState().updateProfile({ username: 'x' })).rejects.toThrow('Username taken');
});
});
describe('FE-STORE-AUTH-030: avatar actions without a signed-in user', () => {
it('uploadAvatar returns the URL but keeps user null', async () => {
vi.spyOn(authApi, 'uploadAvatar').mockResolvedValueOnce({ avatar_url: '/uploads/a.png' });
useAuthStore.setState({ user: null });
const result = await useAuthStore.getState().uploadAvatar(new File(['x'], 'a.png'));
expect(result.avatar_url).toBe('/uploads/a.png');
expect(useAuthStore.getState().user).toBeNull();
});
it('deleteAvatar keeps user null', async () => {
server.use(http.delete('/api/auth/avatar', () => HttpResponse.json({ success: true })));
useAuthStore.setState({ user: null });
await useAuthStore.getState().deleteAvatar();
expect(useAuthStore.getState().user).toBeNull();
});
});
describe('FE-STORE-AUTH-031: demoLogin failure', () => {
it('sets error and stays unauthenticated', async () => {
server.use(http.post('/api/auth/demo-login', () =>
HttpResponse.json({ error: 'Demo disabled' }, { status: 403 })));
await expect(useAuthStore.getState().demoLogin()).rejects.toThrow('Demo disabled');
const state = useAuthStore.getState();
expect(state.error).toBe('Demo disabled');
expect(state.isAuthenticated).toBe(false);
expect(state.isLoading).toBe(false);
});
});
describe('FE-STORE-AUTH-032: remaining app-config setters', () => {
it('updates isPrerelease, appVersion and the three places toggles', () => {
const {
setIsPrerelease, setAppVersion,
setPlacesPhotosEnabled, setPlacesAutocompleteEnabled, setPlacesDetailsEnabled,
} = useAuthStore.getState();
setIsPrerelease(true);
setAppVersion('3.4.0');
setPlacesPhotosEnabled(false);
setPlacesAutocompleteEnabled(false);
setPlacesDetailsEnabled(false);
const state = useAuthStore.getState();
expect(state.isPrerelease).toBe(true);
expect(state.appVersion).toBe('3.4.0');
expect(state.placesPhotosEnabled).toBe(false);
expect(state.placesAutocompleteEnabled).toBe(false);
expect(state.placesDetailsEnabled).toBe(false);
});
});
});
+185 -5
View File
@@ -1,10 +1,11 @@
/**
* videoPoster unit tests (#823). The poster-capture path needs a real <video>
* decoder + canvas, which jsdom does not provide, so we cover the pure file-type
* gate here; poster capture is exercised manually / in the browser.
* videoPoster unit tests (#823). jsdom has no video decoder and no canvas
* rasteriser, so the capture path is driven by hand: document.createElement is
* spied on to hand back the <video>/<canvas> the helper creates, and the media
* events it waits for are fired from the test.
*/
import { describe, it, expect } from 'vitest'
import { isVideoFile } from '../../../src/utils/videoPoster'
import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest'
import { captureVideoPoster, isVideoFile } from '../../../src/utils/videoPoster'
describe('isVideoFile', () => {
it('is true for a video MIME type', () => {
@@ -18,3 +19,182 @@ describe('isVideoFile', () => {
expect(isVideoFile(new File([], 'noext', { type: '' }))).toBe(false)
})
})
interface CanvasStub {
width: number
height: number
getContext: ReturnType<typeof vi.fn>
toBlob: ReturnType<typeof vi.fn>
}
const CLIP = new File(['data'], 'clip.mp4', { type: 'video/mp4' })
const POSTER = new Blob(['jpeg'], { type: 'image/jpeg' })
let video: HTMLVideoElement
let canvas: CanvasStub
let drawImage: ReturnType<typeof vi.fn>
let createObjectURL: ReturnType<typeof vi.fn>
let revokeObjectURL: ReturnType<typeof vi.fn>
/** Fakes the read-only metadata jsdom leaves at 0/NaN. */
function describeMedia(duration: number, width = 1280, height = 720): void {
Object.defineProperty(video, 'duration', { value: duration, configurable: true })
Object.defineProperty(video, 'videoWidth', { value: width, configurable: true })
Object.defineProperty(video, 'videoHeight', { value: height, configurable: true })
}
beforeEach(() => {
vi.useFakeTimers()
drawImage = vi.fn()
canvas = {
width: 0,
height: 0,
getContext: vi.fn(() => ({ drawImage })),
toBlob: vi.fn((cb: BlobCallback) => cb(POSTER)),
}
const realCreate = document.createElement.bind(document)
vi.spyOn(document, 'createElement').mockImplementation((tag: string) => {
if (tag === 'canvas') return canvas as unknown as HTMLCanvasElement
const el = realCreate(tag)
if (tag === 'video') video = el as HTMLVideoElement
return el
})
createObjectURL = vi.fn(() => 'blob:clip')
revokeObjectURL = vi.fn()
vi.stubGlobal('URL', Object.assign(Object.create(URL), { createObjectURL, revokeObjectURL }))
})
afterEach(() => {
vi.useRealTimers()
vi.restoreAllMocks()
vi.unstubAllGlobals()
})
describe('captureVideoPoster', () => {
it('captures a frame just past the start and reports the duration', async () => {
const pending = captureVideoPoster(CLIP)
describeMedia(12.5)
video.onloadedmetadata!(new Event('loadedmetadata'))
// 0.1s in, not the (often black) first frame.
expect(video.currentTime).toBe(0.1)
video.onseeked!(new Event('seeked'))
await expect(pending).resolves.toEqual({ poster: POSTER, durationMs: 12500 })
expect(canvas.width).toBe(1280)
expect(canvas.height).toBe(720)
expect(drawImage).toHaveBeenCalledWith(video, 0, 0, 1280, 720)
expect(canvas.toBlob).toHaveBeenCalledWith(expect.any(Function), 'image/jpeg', 0.8)
expect(revokeObjectURL).toHaveBeenCalledWith('blob:clip')
})
it('seeks to the midpoint of a clip shorter than 0.2s', async () => {
const pending = captureVideoPoster(CLIP)
describeMedia(0.08)
video.onloadedmetadata!(new Event('loadedmetadata'))
expect(video.currentTime).toBe(0.04)
video.onseeked!(new Event('seeked'))
await expect(pending).resolves.toEqual({ poster: POSTER, durationMs: 80 })
})
it('falls back to 640x360 when the stream reports no dimensions', async () => {
const pending = captureVideoPoster(CLIP)
describeMedia(4, 0, 0)
video.onloadedmetadata!(new Event('loadedmetadata'))
video.onseeked!(new Event('seeked'))
await pending
expect(canvas.width).toBe(640)
expect(canvas.height).toBe(360)
})
it('reports a null duration for a stream of unknown length', async () => {
const pending = captureVideoPoster(CLIP)
describeMedia(Infinity)
video.onloadedmetadata!(new Event('loadedmetadata'))
video.onseeked!(new Event('seeked'))
await expect(pending).resolves.toEqual({ poster: POSTER, durationMs: null })
})
it('keeps the duration when no 2d context is available', async () => {
canvas.getContext = vi.fn(() => null)
const pending = captureVideoPoster(CLIP)
describeMedia(3)
video.onloadedmetadata!(new Event('loadedmetadata'))
video.onseeked!(new Event('seeked'))
await expect(pending).resolves.toEqual({ poster: null, durationMs: 3000 })
})
it('keeps the duration when drawing the frame throws', async () => {
drawImage.mockImplementation(() => { throw new Error('tainted') })
const pending = captureVideoPoster(CLIP)
describeMedia(3)
video.onloadedmetadata!(new Event('loadedmetadata'))
video.onseeked!(new Event('seeked'))
await expect(pending).resolves.toEqual({ poster: null, durationMs: 3000 })
})
it('passes a null poster through when toBlob produces nothing', async () => {
canvas.toBlob = vi.fn((cb: BlobCallback) => cb(null))
const pending = captureVideoPoster(CLIP)
describeMedia(3)
video.onloadedmetadata!(new Event('loadedmetadata'))
video.onseeked!(new Event('seeked'))
await expect(pending).resolves.toEqual({ poster: null, durationMs: 3000 })
})
it('resolves empty when the browser cannot decode the file', async () => {
const pending = captureVideoPoster(CLIP)
video.onerror!(new Event('error'))
await expect(pending).resolves.toEqual({ poster: null, durationMs: null })
expect(revokeObjectURL).toHaveBeenCalledWith('blob:clip')
})
it('gives up after ten seconds instead of hanging', async () => {
const pending = captureVideoPoster(CLIP)
await vi.advanceTimersByTimeAsync(10_000)
await expect(pending).resolves.toEqual({ poster: null, durationMs: null })
})
it('resolves once even if several outcomes race', async () => {
const pending = captureVideoPoster(CLIP)
describeMedia(6)
video.onloadedmetadata!(new Event('loadedmetadata'))
video.onseeked!(new Event('seeked'))
video.onerror!(new Event('error'))
await expect(pending).resolves.toEqual({ poster: POSTER, durationMs: 6000 })
expect(revokeObjectURL).toHaveBeenCalledTimes(1)
})
it('still reports the duration when seeking is rejected', async () => {
const pending = captureVideoPoster(CLIP)
describeMedia(9)
Object.defineProperty(video, 'currentTime', {
configurable: true,
get: () => 0,
set: () => { throw new Error('seek not supported') },
})
video.onloadedmetadata!(new Event('loadedmetadata'))
await expect(pending).resolves.toEqual({ poster: null, durationMs: 9000 })
})
})