mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 18:04:18 +00:00
test(dawarich): the integration that shipped without a suite
Dawarich landed on dev untested, which is why release PR #2273 reads 79.0% on SonarCloud's 80% new-code gate: 1352 of the release's 4610 uncovered units are Dawarich's own. 946 cases across 30 files take the surface to 100% in shared, 99.7 in server and 99.6 in client, and the gate to roughly 85%. What stays uncovered is thirteen type-narrowing guards and defensive fallbacks the only caller cannot reach, each argued in the file beside it rather than forced with a cast. No source, config or coverage threshold is touched.
This commit is contained in:
@@ -0,0 +1,721 @@
|
||||
/**
|
||||
* FE-DAWARICH-CONN-001 to FE-DAWARICH-CONN-027: the connection card's one hook.
|
||||
*
|
||||
* Everything the Dawarich connection card does lives here, desktop shell and
|
||||
* phone shell alike, which means everything it can get wrong lives here too.
|
||||
* Four things are worth pinning, and the cases below are grouped around them.
|
||||
*
|
||||
* 1. **The reason-code chain.** Dawarich answers in English and occasionally
|
||||
* quotes the URL back, so the hook renders the server's *code* and keeps the
|
||||
* upstream sentence only as the fallback for a code this build predates. A
|
||||
* regression here crashes nothing: it quietly ships English, or a bare
|
||||
* `dawarich.error.foo` key, onto a German install. Every branch of it is a
|
||||
* sentence a real person reads, so `lastSyncError`, the probe panel, the
|
||||
* private-IP warning and all four error toasts each get their own case.
|
||||
* 2. **"Blank means keep the stored key".** The key field is never prefilled,
|
||||
* so an untouched field must leave `apiKey` out of the payload entirely.
|
||||
* Sending `apiKey: ''` instead would wipe a working connection on the next
|
||||
* save of an unrelated switch.
|
||||
* 3. **The flags nobody sets by hand.** `canSave` (an address alone is not a
|
||||
* connection), `alreadyRunning` (a sync in flight has no result yet, so
|
||||
* "0 new stays" would be a claim rather than a report), and the three
|
||||
* in-flight booleans the buttons disable themselves with.
|
||||
* 4. **The unmount guard** on the initial read, the reason a card closed
|
||||
* mid-request does not write into a dead component.
|
||||
*
|
||||
* The API and the toaster are mocked, the way the neighbouring
|
||||
* `useDawarichSuggestions` test does it. Translation is not: `en` is bundled
|
||||
* statically, so the real provider answers synchronously, and the hook's
|
||||
* fallbacks depend on `t()` returning the key untouched for a string this build
|
||||
* does not have, which only the real one does.
|
||||
*/
|
||||
import { createElement, type ReactNode } from 'react'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { DawarichCapabilities, DawarichConnection, DawarichStatus } from '@trek/shared'
|
||||
import { TranslationProvider } from '../i18n/TranslationContext'
|
||||
import { useDawarichConnection } from './useDawarichConnection'
|
||||
|
||||
const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }
|
||||
vi.mock('../components/shared/Toast', () => ({ useToast: () => toast, default: () => toast }))
|
||||
|
||||
const api = {
|
||||
getSettings: vi.fn(),
|
||||
saveSettings: vi.fn(),
|
||||
test: vi.fn(),
|
||||
syncNow: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
}
|
||||
vi.mock('../api/dawarich', () => ({
|
||||
dawarichApi: {
|
||||
getSettings: (...args: unknown[]) => api.getSettings(...args),
|
||||
saveSettings: (...args: unknown[]) => api.saveSettings(...args),
|
||||
test: (...args: unknown[]) => api.test(...args),
|
||||
syncNow: (...args: unknown[]) => api.syncNow(...args),
|
||||
disconnect: (...args: unknown[]) => api.disconnect(...args),
|
||||
},
|
||||
}))
|
||||
|
||||
const CAPS: DawarichCapabilities = {
|
||||
visits: true,
|
||||
tracks: true,
|
||||
points: false,
|
||||
locations: true,
|
||||
visitedCities: false,
|
||||
visitUpdatedAt: false,
|
||||
visitCountryCode: false,
|
||||
serverVersion: '1.14.4',
|
||||
probedAt: '2026-09-01T08:00:00.000Z',
|
||||
}
|
||||
|
||||
/**
|
||||
* A connected instance with a clean history. Written out in full rather than
|
||||
* cast from a fragment so the day the contract grows a field, this file is one
|
||||
* of the places that has to answer for it.
|
||||
*/
|
||||
function connection(over: Partial<DawarichConnection> = {}): DawarichConnection {
|
||||
return {
|
||||
url: 'https://dawarich.example',
|
||||
apiKeyMasked: '****abcd',
|
||||
allowInsecureTls: false,
|
||||
syncEnabled: true,
|
||||
connected: true,
|
||||
lastSyncAt: '2026-09-01T07:00:00.000Z',
|
||||
lastSyncState: 'ok',
|
||||
lastSyncError: null,
|
||||
capabilities: CAPS,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
/** A promise this test controls the settling of, to pin down state mid-flight. */
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res
|
||||
reject = rej
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
const wrapper = ({ children }: { children: ReactNode }) => createElement(TranslationProvider, null, children)
|
||||
|
||||
function mount() {
|
||||
return renderHook(() => useDawarichConnection(), { wrapper })
|
||||
}
|
||||
|
||||
async function mounted(data: DawarichConnection = connection()) {
|
||||
api.getSettings.mockResolvedValue(data)
|
||||
const hook = mount()
|
||||
await waitFor(() => expect(hook.result.current.loading).toBe(false))
|
||||
return hook
|
||||
}
|
||||
|
||||
// The shipped English for the keys this hook reaches for. Written out rather
|
||||
// than read back from the bundle so a reader of this file sees the sentence that
|
||||
// ends up on screen, and so a reworded string is a decision somebody makes here
|
||||
// too. The private-IP warning is the one exception: it is long enough that
|
||||
// transcribing it would test the transcription, so it is asserted by its parts.
|
||||
const EN = {
|
||||
probeOk: (count: number) => `Connected. ${count} stays found in the last 30 days.`,
|
||||
probeFailed: 'Could not reach Dawarich.',
|
||||
saved: 'Dawarich connection saved',
|
||||
saveError: 'Could not save the connection',
|
||||
disconnected: 'Dawarich disconnected',
|
||||
synced: (count: number) => `${count} new stays found`,
|
||||
syncError: 'Could not read Dawarich',
|
||||
syncRunning: 'A check is already running',
|
||||
unreachable: 'TREK could not reach that address.',
|
||||
unauthorized: 'Dawarich rejected the API key.',
|
||||
unknown: 'Something went wrong talking to Dawarich.',
|
||||
}
|
||||
|
||||
/** The last thing a toaster was handed, for the assertions that read a sentence apart. */
|
||||
function lastToast(fn: typeof toast.warning): string {
|
||||
const calls = fn.mock.calls
|
||||
return calls[calls.length - 1]?.[0] as string
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
toast.success.mockReset()
|
||||
toast.error.mockReset()
|
||||
toast.info.mockReset()
|
||||
toast.warning.mockReset()
|
||||
api.getSettings.mockReset().mockResolvedValue(connection())
|
||||
api.saveSettings.mockReset().mockResolvedValue({ success: true })
|
||||
api.test.mockReset().mockResolvedValue({ connected: true, visitCount: 4, capabilities: CAPS })
|
||||
api.syncNow.mockReset().mockResolvedValue({ state: 'ok', created: 2, updated: 1, missing: 0 })
|
||||
api.disconnect.mockReset().mockResolvedValue({ success: true })
|
||||
})
|
||||
|
||||
describe('useDawarichConnection: the initial read', () => {
|
||||
it('FE-DAWARICH-CONN-001: starts loading and then hydrates every field from the stored connection', async () => {
|
||||
const settings = deferred<DawarichConnection>()
|
||||
api.getSettings.mockReturnValue(settings.promise)
|
||||
const { result } = mount()
|
||||
|
||||
expect(result.current.loading).toBe(true)
|
||||
expect(result.current.url).toBe('')
|
||||
expect(result.current.connected).toBe(false)
|
||||
|
||||
await act(async () => {
|
||||
settings.resolve(connection({ lastSyncState: 'partial', lastSyncError: 'unauthorized' }))
|
||||
await settings.promise
|
||||
})
|
||||
|
||||
expect(result.current.loading).toBe(false)
|
||||
expect(result.current.url).toBe('https://dawarich.example')
|
||||
expect(result.current.connected).toBe(true)
|
||||
expect(result.current.syncEnabled).toBe(true)
|
||||
expect(result.current.allowInsecureTls).toBe(false)
|
||||
expect(result.current.lastSyncAt).toBe('2026-09-01T07:00:00.000Z')
|
||||
expect(result.current.lastSyncState).toBe('partial')
|
||||
expect(result.current.lastSyncError).toBe(EN.unauthorized)
|
||||
expect(result.current.capabilities).toEqual(CAPS)
|
||||
// The stored key never leaves the server, so the field is blank even though
|
||||
// the connection is live. Everything below about `canSave` follows from it.
|
||||
expect(result.current.apiKey).toBe('')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-002: an instance that was never connected leaves the card empty and keeps sync switched off', async () => {
|
||||
const { result } = await mounted(connection({
|
||||
url: '',
|
||||
allowInsecureTls: true,
|
||||
syncEnabled: false,
|
||||
connected: false,
|
||||
lastSyncAt: null,
|
||||
lastSyncState: 'never',
|
||||
capabilities: null,
|
||||
}))
|
||||
|
||||
expect(result.current.url).toBe('')
|
||||
expect(result.current.allowInsecureTls).toBe(true)
|
||||
// `syncEnabled` defaults to on, so an explicit false is the one value that
|
||||
// has to survive the round trip intact.
|
||||
expect(result.current.syncEnabled).toBe(false)
|
||||
expect(result.current.connected).toBe(false)
|
||||
expect(result.current.capabilities).toBeNull()
|
||||
expect(result.current.lastSyncAt).toBeNull()
|
||||
expect(result.current.lastSyncError).toBeNull()
|
||||
expect(result.current.canSave).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-003: a failed read of our own settings clears loading without blaming the instance', async () => {
|
||||
api.getSettings.mockRejectedValue(new Error('500'))
|
||||
const { result } = mount()
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false))
|
||||
expect(result.current.url).toBe('')
|
||||
expect(result.current.connected).toBe(false)
|
||||
expect(result.current.lastSyncState).toBe('never')
|
||||
// Our own endpoint failing is a TREK problem. An error toast here would send
|
||||
// the reader off editing a URL that was never at fault.
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-004: settings that arrive after the card is gone are dropped, not written into a dead component', async () => {
|
||||
const settings = deferred<DawarichConnection>()
|
||||
api.getSettings.mockReturnValue(settings.promise)
|
||||
const { result, unmount } = mount()
|
||||
|
||||
unmount()
|
||||
await act(async () => {
|
||||
settings.resolve(connection())
|
||||
await settings.promise
|
||||
})
|
||||
|
||||
// The last rendered values are the pre-flight ones: nothing was set after
|
||||
// the unmount, not even the loading flag in the `finally`.
|
||||
expect(result.current.loading).toBe(true)
|
||||
expect(result.current.url).toBe('')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-005: the last sync error is rendered from its code, and an unrecognised code still gets a sentence', async () => {
|
||||
const known = await mounted(connection({ lastSyncState: 'failed', lastSyncError: 'unreachable' }))
|
||||
expect(known.result.current.lastSyncError).toBe(EN.unreachable)
|
||||
|
||||
// A code from a server newer than this build. It must not reach the screen
|
||||
// as the bare key, which is what happens the day the fallback goes.
|
||||
const ahead = await mounted(connection({ lastSyncState: 'failed', lastSyncError: 'quota_exhausted' }))
|
||||
expect(ahead.result.current.lastSyncError).toBe(EN.unknown)
|
||||
expect(ahead.result.current.lastSyncError).not.toBe('dawarich.error.quota_exhausted')
|
||||
|
||||
const clean = await mounted(connection({ lastSyncError: null }))
|
||||
expect(clean.result.current.lastSyncError).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDawarichConnection: the save gate', () => {
|
||||
it('FE-DAWARICH-CONN-006: saving needs an address plus either a live connection or a freshly typed key', async () => {
|
||||
const { result } = await mounted(connection({
|
||||
url: '',
|
||||
connected: false,
|
||||
capabilities: null,
|
||||
lastSyncAt: null,
|
||||
lastSyncState: 'never',
|
||||
}))
|
||||
expect(result.current.canSave).toBe(false)
|
||||
|
||||
act(() => result.current.setUrl(' '))
|
||||
expect(result.current.canSave).toBe(false)
|
||||
|
||||
// An address on its own: nothing stored, nothing typed, so there is no key
|
||||
// to save it with.
|
||||
act(() => result.current.setUrl('https://dawarich.example'))
|
||||
expect(result.current.canSave).toBe(false)
|
||||
|
||||
act(() => result.current.setApiKey(' '))
|
||||
expect(result.current.canSave).toBe(false)
|
||||
|
||||
act(() => result.current.setApiKey('k-123'))
|
||||
expect(result.current.canSave).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-007: an already connected instance stays saveable with the key field left blank', async () => {
|
||||
const { result } = await mounted()
|
||||
expect(result.current.apiKey).toBe('')
|
||||
expect(result.current.canSave).toBe(true)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-008: both switches flip, and the save they trigger carries no key at all', async () => {
|
||||
const { result } = await mounted()
|
||||
|
||||
act(() => result.current.toggleInsecureTls())
|
||||
act(() => result.current.toggleSync())
|
||||
expect(result.current.allowInsecureTls).toBe(true)
|
||||
expect(result.current.syncEnabled).toBe(false)
|
||||
|
||||
await act(async () => { await result.current.save() })
|
||||
|
||||
// No `apiKey` property whatsoever: an empty string would clear the stored
|
||||
// key, and this save was about two switches.
|
||||
expect(api.saveSettings).toHaveBeenCalledWith({
|
||||
url: 'https://dawarich.example',
|
||||
allowInsecureTls: true,
|
||||
syncEnabled: false,
|
||||
})
|
||||
|
||||
act(() => result.current.toggleInsecureTls())
|
||||
expect(result.current.allowInsecureTls).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDawarichConnection: save', () => {
|
||||
it('FE-DAWARICH-CONN-009: save trims the address, sends the typed key once, re-reads the connection and clears the field', async () => {
|
||||
const { result } = await mounted(connection({
|
||||
connected: false,
|
||||
capabilities: null,
|
||||
lastSyncState: 'failed',
|
||||
lastSyncError: 'unreachable',
|
||||
}))
|
||||
act(() => {
|
||||
result.current.setUrl(' https://new.example ')
|
||||
result.current.setApiKey(' k-123 ')
|
||||
})
|
||||
|
||||
const pending = deferred<{ success: boolean }>()
|
||||
api.saveSettings.mockReturnValue(pending.promise)
|
||||
api.getSettings.mockResolvedValue(connection({
|
||||
url: 'https://new.example',
|
||||
connected: true,
|
||||
lastSyncState: 'ok',
|
||||
lastSyncError: null,
|
||||
}))
|
||||
|
||||
let done!: Promise<void>
|
||||
act(() => { done = result.current.save() })
|
||||
expect(result.current.saving).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
pending.resolve({ success: true })
|
||||
await done
|
||||
})
|
||||
|
||||
expect(api.saveSettings).toHaveBeenCalledWith({
|
||||
url: 'https://new.example',
|
||||
allowInsecureTls: false,
|
||||
syncEnabled: true,
|
||||
apiKey: 'k-123',
|
||||
})
|
||||
// Cleared, so the next save of an unrelated switch does not resend it.
|
||||
expect(result.current.apiKey).toBe('')
|
||||
expect(result.current.connected).toBe(true)
|
||||
expect(result.current.capabilities).toEqual(CAPS)
|
||||
expect(result.current.lastSyncState).toBe('ok')
|
||||
expect(result.current.lastSyncError).toBeNull()
|
||||
expect(result.current.saving).toBe(false)
|
||||
expect(toast.success).toHaveBeenCalledWith(EN.saved)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-010: a save the server accepts but cannot connect with flips the card back to disconnected', async () => {
|
||||
const { result } = await mounted()
|
||||
expect(result.current.connected).toBe(true)
|
||||
|
||||
api.getSettings.mockResolvedValue(connection({
|
||||
connected: false,
|
||||
capabilities: null,
|
||||
lastSyncState: 'failed',
|
||||
lastSyncError: 'unauthorized',
|
||||
}))
|
||||
await act(async () => { await result.current.save() })
|
||||
|
||||
// A saved record and a working connection are two different things, and the
|
||||
// badge follows the second one.
|
||||
expect(result.current.connected).toBe(false)
|
||||
expect(result.current.capabilities).toBeNull()
|
||||
expect(result.current.lastSyncError).toBe(EN.unauthorized)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-011: a save that answers with an empty body still counts as saved', async () => {
|
||||
const { result } = await mounted()
|
||||
// A 204 arrives as no body at all; the warning branch must not trip on it.
|
||||
api.saveSettings.mockResolvedValue(undefined)
|
||||
|
||||
await act(async () => { await result.current.save() })
|
||||
|
||||
expect(toast.success).toHaveBeenCalledWith(EN.saved)
|
||||
expect(toast.warning).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-012: a save whose follow-up read fails keeps the card as it was and still reports success', async () => {
|
||||
const { result } = await mounted()
|
||||
api.getSettings.mockRejectedValue(new Error('boom'))
|
||||
|
||||
await act(async () => { await result.current.save() })
|
||||
|
||||
// The write landed. Losing the refresh must not blank the badge, the
|
||||
// capabilities or the sync history that are still true.
|
||||
expect(result.current.connected).toBe(true)
|
||||
expect(result.current.capabilities).toEqual(CAPS)
|
||||
expect(result.current.lastSyncState).toBe('ok')
|
||||
expect(toast.success).toHaveBeenCalledWith(EN.saved)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-013: the private-IP warning is rendered from its code, with the address the server resolved', async () => {
|
||||
const serverSentence = 'Dawarich resolved to 192.168.1.4, which is a private address.'
|
||||
const { result } = await mounted()
|
||||
api.saveSettings.mockResolvedValue({
|
||||
success: true,
|
||||
warning: serverSentence,
|
||||
warningCode: 'private_ip',
|
||||
warningIp: '192.168.1.4',
|
||||
})
|
||||
|
||||
await act(async () => { await result.current.save() })
|
||||
|
||||
const warned = lastToast(toast.warning)
|
||||
expect(warned).toContain('private IP (192.168.1.4)')
|
||||
// The fix belongs in the sentence, and it is the half a self-hoster needs.
|
||||
expect(warned).toContain('ALLOW_INTERNAL_NETWORK')
|
||||
// The server's own English never reaches the reader while the code is known.
|
||||
expect(warned).not.toBe(serverSentence)
|
||||
expect(toast.success).not.toHaveBeenCalled()
|
||||
|
||||
// A coded warning with no address attached still translates; the slot is
|
||||
// filled with nothing rather than left as the literal "{ip}".
|
||||
api.saveSettings.mockResolvedValue({ success: true, warning: serverSentence, warningCode: 'private_ip' })
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(lastToast(toast.warning)).toContain('private IP ()')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-014: a warning code this build has no string for falls back to the server sentence', async () => {
|
||||
const { result } = await mounted()
|
||||
api.saveSettings.mockResolvedValue({
|
||||
success: true,
|
||||
warning: 'Heads up: that host answers very slowly.',
|
||||
warningCode: 'slow_host',
|
||||
warningIp: '10.0.0.9',
|
||||
})
|
||||
|
||||
await act(async () => { await result.current.save() })
|
||||
// English prose beats a raw `dawarich.warning.slow_host` on the screen.
|
||||
expect(toast.warning).toHaveBeenCalledWith('Heads up: that host answers very slowly.')
|
||||
|
||||
// An older server that attaches prose without a code at all.
|
||||
api.saveSettings.mockResolvedValue({ success: true, warning: 'Saved, but that address looks odd.' })
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(toast.warning).toHaveBeenLastCalledWith('Saved, but that address looks odd.')
|
||||
|
||||
// A warning is not a success: the card must not say both.
|
||||
expect(toast.success).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-015: a rejected save is reported by code first, then by the server sentence, then generically', async () => {
|
||||
const { result } = await mounted()
|
||||
|
||||
api.saveSettings.mockRejectedValue({
|
||||
response: { data: { code: 'unauthorized', error: 'Dawarich answered 401 for https://dawarich.example' } },
|
||||
})
|
||||
await act(async () => { await result.current.save() })
|
||||
// The code wins over the prose, which is English and quotes the URL back.
|
||||
expect(toast.error).toHaveBeenLastCalledWith(EN.unauthorized)
|
||||
|
||||
api.saveSettings.mockRejectedValue({
|
||||
response: { data: { code: 'quota_exhausted', error: 'Quota exhausted until 14:00' } },
|
||||
})
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(toast.error).toHaveBeenLastCalledWith('Quota exhausted until 14:00')
|
||||
|
||||
// Not our envelope at all: a numeric code is ignored, the prose still reads.
|
||||
api.saveSettings.mockRejectedValue({ response: { data: { code: 409, error: 'conflict' } } })
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(toast.error).toHaveBeenLastCalledWith('conflict')
|
||||
|
||||
// Nothing usable anywhere in the error (a transport failure, typically).
|
||||
api.saveSettings.mockRejectedValue(new Error('Network Error'))
|
||||
await act(async () => { await result.current.save() })
|
||||
expect(toast.error).toHaveBeenLastCalledWith(EN.saveError)
|
||||
|
||||
expect(result.current.saving).toBe(false)
|
||||
expect(toast.success).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-027: a rejection carrying no error object at all still reaches the reader as a sentence', async () => {
|
||||
const { result } = await mounted()
|
||||
// Not a shape axios produces on its own, but the optional chain at the top
|
||||
// of errorText() is there for it: an aborted or torn-down call rejects with
|
||||
// nothing, and reading .response off that would throw inside the catch,
|
||||
// which loses the toast entirely and rejects save() into whoever pressed
|
||||
// the button. The generic sentence is the floor, and it has to hold.
|
||||
api.saveSettings.mockRejectedValue(undefined)
|
||||
|
||||
await act(async () => { await result.current.save() })
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(EN.saveError)
|
||||
expect(result.current.saving).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDawarichConnection: the connection probe', () => {
|
||||
it('FE-DAWARICH-CONN-016: a successful probe reports the count in the panel and the toast, and adopts what it found', async () => {
|
||||
const { result } = await mounted(connection({ connected: false, capabilities: null }))
|
||||
act(() => {
|
||||
result.current.setUrl(' https://probe.example ')
|
||||
result.current.setApiKey('k-123')
|
||||
})
|
||||
|
||||
const probe = deferred<DawarichStatus>()
|
||||
api.test.mockReturnValue(probe.promise)
|
||||
let done!: Promise<void>
|
||||
act(() => { done = result.current.test() })
|
||||
expect(result.current.testing).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
probe.resolve({ connected: true, visitCount: 12, capabilities: CAPS })
|
||||
await done
|
||||
})
|
||||
|
||||
// The probe runs against what is typed, not against what is stored. That is
|
||||
// the whole point of testing before saving.
|
||||
expect(api.test).toHaveBeenCalledWith({
|
||||
url: 'https://probe.example',
|
||||
allowInsecureTls: false,
|
||||
apiKey: 'k-123',
|
||||
})
|
||||
expect(result.current.connected).toBe(true)
|
||||
expect(result.current.capabilities).toEqual(CAPS)
|
||||
expect(result.current.probeMessage).toBe(EN.probeOk(12))
|
||||
expect(toast.success).toHaveBeenCalledWith(EN.probeOk(12))
|
||||
expect(result.current.testing).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-017: a probe that answers without a count or capabilities says zero and keeps what was known', async () => {
|
||||
const { result } = await mounted()
|
||||
api.test.mockResolvedValue({ connected: true })
|
||||
|
||||
await act(async () => { await result.current.test() })
|
||||
|
||||
// "Connected" with no number reads the same as a reachable instance holding
|
||||
// nothing at all, which is a genuinely different situation.
|
||||
expect(result.current.probeMessage).toBe(EN.probeOk(0))
|
||||
// A probe that reported no capabilities must not erase the stored ones.
|
||||
expect(result.current.capabilities).toEqual(CAPS)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-018: a refused probe puts the reason in the panel and keeps the toast to one line', async () => {
|
||||
const { result } = await mounted()
|
||||
api.test.mockResolvedValue({
|
||||
connected: false,
|
||||
error: 'unreachable',
|
||||
errorDetail: 'self-signed certificate',
|
||||
})
|
||||
|
||||
await act(async () => { await result.current.test() })
|
||||
|
||||
expect(result.current.connected).toBe(false)
|
||||
// The detail is what separates "the host is down" from "we rejected the
|
||||
// certificate", and the self-hoster needs it to know which knob to turn.
|
||||
expect(result.current.probeMessage).toBe(`${EN.unreachable} (self-signed certificate)`)
|
||||
expect(toast.error).toHaveBeenCalledWith(EN.unreachable)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-019: a refused probe with no reason at all still says something, and an unrecognised code does too', async () => {
|
||||
const { result } = await mounted()
|
||||
|
||||
api.test.mockResolvedValue({ connected: false })
|
||||
await act(async () => { await result.current.test() })
|
||||
expect(result.current.probeMessage).toBe(EN.probeFailed)
|
||||
|
||||
api.test.mockResolvedValue({ connected: false, error: 'quota_exhausted' })
|
||||
await act(async () => { await result.current.test() })
|
||||
expect(result.current.probeMessage).toBe(EN.unknown)
|
||||
expect(toast.success).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-020: a thrown probe clears the stale panel line first, then reports the coded reason or a generic one', async () => {
|
||||
const { result } = await mounted()
|
||||
api.test.mockResolvedValue({ connected: true, visitCount: 3 })
|
||||
await act(async () => { await result.current.test() })
|
||||
expect(result.current.probeMessage).toBe(EN.probeOk(3))
|
||||
|
||||
const thrown = deferred<DawarichStatus>()
|
||||
api.test.mockReturnValue(thrown.promise)
|
||||
let done!: Promise<void>
|
||||
act(() => { done = result.current.test() })
|
||||
// A success belonging to the previous address must not sit under a probe of
|
||||
// the one being typed now.
|
||||
expect(result.current.probeMessage).toBeNull()
|
||||
|
||||
await act(async () => {
|
||||
thrown.reject({ response: { data: { code: 'unauthorized' } } })
|
||||
await done
|
||||
})
|
||||
expect(result.current.probeMessage).toBe(EN.unauthorized)
|
||||
expect(toast.error).toHaveBeenLastCalledWith(EN.unauthorized)
|
||||
|
||||
api.test.mockRejectedValue(new Error('Network Error'))
|
||||
await act(async () => { await result.current.test() })
|
||||
expect(result.current.probeMessage).toBe(EN.probeFailed)
|
||||
expect(result.current.testing).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDawarichConnection: sync now', () => {
|
||||
it('FE-DAWARICH-CONN-021: a sync that is already running says so and invents no result', async () => {
|
||||
const { result } = await mounted(connection({ lastSyncState: 'partial', lastSyncError: 'unreachable' }))
|
||||
api.syncNow.mockResolvedValue({ state: 'running', created: 0, updated: 0, missing: 0, alreadyRunning: true })
|
||||
|
||||
await act(async () => { await result.current.syncNow() })
|
||||
|
||||
expect(toast.info).toHaveBeenCalledWith(EN.syncRunning)
|
||||
// Nothing finished, so nothing about the last run may move, least of all a
|
||||
// "0 new stays" that would read as this run's answer.
|
||||
expect(result.current.lastSyncAt).toBe('2026-09-01T07:00:00.000Z')
|
||||
expect(result.current.lastSyncState).toBe('partial')
|
||||
expect(result.current.lastSyncError).toBe(EN.unreachable)
|
||||
expect(toast.success).not.toHaveBeenCalled()
|
||||
expect(result.current.syncing).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-022: a finished sync stamps the time, takes the server state and clears the previous error', async () => {
|
||||
const { result } = await mounted(connection({
|
||||
lastSyncAt: '2026-08-01T00:00:00.000Z',
|
||||
lastSyncState: 'failed',
|
||||
lastSyncError: 'unreachable',
|
||||
}))
|
||||
|
||||
const run = deferred<{ state: string; created: number; updated: number; missing: number }>()
|
||||
api.syncNow.mockReturnValue(run.promise)
|
||||
const before = Date.now()
|
||||
let done!: Promise<void>
|
||||
act(() => { done = result.current.syncNow() })
|
||||
expect(result.current.syncing).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
run.resolve({ state: 'partial', created: 3, updated: 1, missing: 2 })
|
||||
await done
|
||||
})
|
||||
|
||||
// A partial run is not a clean one, so the server's word is kept rather than
|
||||
// flattened to "ok", but the stale failure underneath it has to go.
|
||||
expect(result.current.lastSyncState).toBe('partial')
|
||||
expect(result.current.lastSyncError).toBeNull()
|
||||
expect(Date.parse(result.current.lastSyncAt ?? '')).toBeGreaterThanOrEqual(before)
|
||||
expect(toast.success).toHaveBeenCalledWith(EN.synced(3))
|
||||
expect(result.current.syncing).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-023: a sync answer without a state or a count is treated as a clean run that found nothing', async () => {
|
||||
const { result } = await mounted(connection({ lastSyncAt: null, lastSyncState: 'never' }))
|
||||
api.syncNow.mockResolvedValue({})
|
||||
|
||||
await act(async () => { await result.current.syncNow() })
|
||||
|
||||
expect(result.current.lastSyncState).toBe('ok')
|
||||
expect(result.current.lastSyncAt).not.toBeNull()
|
||||
expect(toast.success).toHaveBeenCalledWith(EN.synced(0))
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-024: a sync that throws marks the state failed and reports the coded reason, or a generic one', async () => {
|
||||
const { result } = await mounted()
|
||||
|
||||
api.syncNow.mockRejectedValue({ response: { data: { code: 'unauthorized' } } })
|
||||
await act(async () => { await result.current.syncNow() })
|
||||
// The card has to stop claiming the last run was fine.
|
||||
expect(result.current.lastSyncState).toBe('failed')
|
||||
expect(toast.error).toHaveBeenCalledWith(EN.unauthorized)
|
||||
|
||||
// An envelope whose `error` is an object rather than a sentence: unusable,
|
||||
// so the generic line stands instead of "[object Object]".
|
||||
api.syncNow.mockRejectedValue({ response: { data: { error: { reason: 'locked' } } } })
|
||||
await act(async () => { await result.current.syncNow() })
|
||||
expect(toast.error).toHaveBeenLastCalledWith(EN.syncError)
|
||||
expect(result.current.syncing).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDawarichConnection: disconnect', () => {
|
||||
it('FE-DAWARICH-CONN-025: disconnect empties the card down to the probe message', async () => {
|
||||
const { result } = await mounted(connection({ lastSyncState: 'failed', lastSyncError: 'unreachable' }))
|
||||
act(() => result.current.setApiKey('k-123'))
|
||||
api.test.mockResolvedValue({ connected: true, visitCount: 1 })
|
||||
await act(async () => { await result.current.test() })
|
||||
expect(result.current.probeMessage).not.toBeNull()
|
||||
|
||||
const drop = deferred<{ success: boolean }>()
|
||||
api.disconnect.mockReturnValue(drop.promise)
|
||||
let done!: Promise<void>
|
||||
act(() => { done = result.current.disconnect() })
|
||||
// Disconnect borrows the saving flag: both writes touch the same record, and
|
||||
// the card disables the same buttons for either.
|
||||
expect(result.current.saving).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
drop.resolve({ success: true })
|
||||
await done
|
||||
})
|
||||
|
||||
// Every leftover matters here: a stale probe line or sync history under an
|
||||
// empty form reads as a connection that is still half there.
|
||||
expect(result.current.url).toBe('')
|
||||
expect(result.current.apiKey).toBe('')
|
||||
expect(result.current.connected).toBe(false)
|
||||
expect(result.current.capabilities).toBeNull()
|
||||
expect(result.current.lastSyncAt).toBeNull()
|
||||
expect(result.current.lastSyncState).toBe('never')
|
||||
expect(result.current.lastSyncError).toBeNull()
|
||||
expect(result.current.probeMessage).toBeNull()
|
||||
expect(result.current.canSave).toBe(false)
|
||||
expect(result.current.saving).toBe(false)
|
||||
expect(toast.success).toHaveBeenCalledWith(EN.disconnected)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-CONN-026: a failed disconnect leaves the connection on screen rather than pretending it is gone', async () => {
|
||||
const { result } = await mounted()
|
||||
|
||||
api.disconnect.mockRejectedValue({ response: { data: { error: 'Database is locked' } } })
|
||||
await act(async () => { await result.current.disconnect() })
|
||||
|
||||
expect(result.current.url).toBe('https://dawarich.example')
|
||||
expect(result.current.connected).toBe(true)
|
||||
expect(result.current.capabilities).toEqual(CAPS)
|
||||
expect(toast.error).toHaveBeenCalledWith('Database is locked')
|
||||
expect(result.current.saving).toBe(false)
|
||||
|
||||
api.disconnect.mockRejectedValue(new Error('offline'))
|
||||
await act(async () => { await result.current.disconnect() })
|
||||
expect(toast.error).toHaveBeenLastCalledWith(EN.saveError)
|
||||
expect(result.current.connected).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,396 @@
|
||||
/**
|
||||
* FE-DAWARICH-JTRAIL-001 to FE-DAWARICH-JTRAIL-013: the recorded route a
|
||||
* journal draws over its own dates (#2279).
|
||||
*
|
||||
* This hook is the one place a journal reaches across the network to somebody's
|
||||
* self-hosted location history, and almost everything worth pinning about it is
|
||||
* a thing that must NOT happen.
|
||||
*
|
||||
* The gate first. Three separate switches have to agree before a single request
|
||||
* leaves the browser (the journal's own "show trip tracks" preference, the
|
||||
* Dawarich addon being enabled on the instance, and the journal actually
|
||||
* covering some dates), and each of them is a promise to the user: a journal
|
||||
* whose tracks are switched off must not go and fetch a GPS archive anyway.
|
||||
* They are `&&`-chained, so a regression in any one of them looks identical on
|
||||
* screen (nothing is drawn) while the request goes out regardless. Only the
|
||||
* absence of the call catches that, which is why the first three cases assert
|
||||
* on `windowTrack` never having been called rather than on what was rendered.
|
||||
*
|
||||
* Then the window. A `Set` has no order and a journal's dates are accumulated
|
||||
* from several trips, so the earliest and latest day are found by sorting, not
|
||||
* by trusting insertion order. Get that wrong and the fetched span is some
|
||||
* arbitrary pair of days out of the middle of the journey.
|
||||
*
|
||||
* Then the shape. The overlay rides the journey map's existing `JourneyTrack[]`
|
||||
* layer, which keys its polylines on `place_id`. The synthetic ids are negative
|
||||
* precisely so they can never collide with a real place's. A collision would
|
||||
* make the map drop or duplicate a line rather than fail loudly.
|
||||
*
|
||||
* Finally the four endings, because the journal map has no other way to say
|
||||
* what happened: a route, nothing recorded, the instance not answering, and the
|
||||
* device being offline. The last one is checked twice, before the request and
|
||||
* again when it fails, so a connection that dies mid-flight is reported as
|
||||
* "offline" rather than blamed on the user's Dawarich instance.
|
||||
*
|
||||
* The late-answer cases exist because this hook lives on a page the user leaves
|
||||
* and a switch they flip: an in-flight request that lands after the layer has
|
||||
* been switched off must not paint a line onto a map that no longer wants one.
|
||||
*
|
||||
* That switch going off after a route is already drawn is its own case. The
|
||||
* line has to leave the map with it rather than linger until something else
|
||||
* happens to clear it, and turning it back on has to ask again rather than
|
||||
* replay a recording that may have grown in the meantime. This hook keeps no
|
||||
* cache, deliberately, because a cached copy of somebody's location history is
|
||||
* the thing the integration exists not to keep.
|
||||
*/
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { DawarichTrack, DawarichTrackDay } from '@trek/shared'
|
||||
|
||||
const { windowTrack, offline } = vi.hoisted(() => ({ windowTrack: vi.fn(), offline: vi.fn() }))
|
||||
vi.mock('../repo/dawarichRepo', () => ({ dawarichRepo: { windowTrack } }))
|
||||
// Only `isEffectivelyOffline` is swapped out. `addonStore` reaches `api/client`,
|
||||
// which imports from this module as well, and a factory that named a single
|
||||
// export would hand every other importer in the graph `undefined`.
|
||||
vi.mock('../sync/networkMode', async importOriginal => ({
|
||||
...(await importOriginal<typeof import('../sync/networkMode')>()),
|
||||
isEffectivelyOffline: offline,
|
||||
}))
|
||||
|
||||
import { useAddonStore } from '../store/addonStore'
|
||||
import { DAWARICH_DAY_COLORS } from '../components/Map/dawarichTrail'
|
||||
import { useDawarichJournalTrail } from './useDawarichJournalTrail'
|
||||
|
||||
const DAY_ONE = '2026-03-03'
|
||||
const DAY_TWO = '2026-03-04'
|
||||
const DAY_THREE = '2026-03-05'
|
||||
|
||||
const FETCHED_AT = '2026-03-06T09:12:00.000Z'
|
||||
|
||||
const journalDates = (...days: string[]) => new Set(days)
|
||||
|
||||
function segment(points: Array<[number, number]>) {
|
||||
return {
|
||||
points,
|
||||
mode: 'walking',
|
||||
startedAt: `${DAY_ONE}T08:00:00Z`,
|
||||
endedAt: `${DAY_ONE}T09:00:00Z`,
|
||||
distanceMeters: 1200,
|
||||
}
|
||||
}
|
||||
|
||||
/** One recorded day with a single two-point line: the smallest thing that draws. */
|
||||
const day = (date: string, points: Array<[number, number]> = [[53.5, 10.0], [53.6, 10.1]]): DawarichTrackDay =>
|
||||
({ date, segments: [segment(points)] })
|
||||
|
||||
function track(over: Partial<DawarichTrack> = {}): DawarichTrack {
|
||||
return { days: [], source: 'tracks', fetchedAt: FETCHED_AT, pointCount: 0, truncated: false, ...over }
|
||||
}
|
||||
|
||||
/**
|
||||
* A request left hanging, so the world can change underneath it: the dates
|
||||
* edited, the layer switched off, the network lost. None of that is observable
|
||||
* against a promise that has already resolved.
|
||||
*/
|
||||
function held() {
|
||||
let settle!: (value: DawarichTrack) => void
|
||||
let fail!: (reason: Error) => void
|
||||
const promise = new Promise<DawarichTrack>((resolve, reject) => { settle = resolve; fail = reject })
|
||||
return { promise, settle, fail }
|
||||
}
|
||||
|
||||
/**
|
||||
* Land a held request and let the hook's whole `.then`/`.catch` chain run
|
||||
* before anything is asserted. Two ticks, because a rejection travels through
|
||||
* the `.then` that has no rejection handler before it reaches the `.catch`.
|
||||
*
|
||||
* Worth being exact about: the late-answer cases assert that nothing changed,
|
||||
* so a chain that had not run yet would pass them for the wrong reason and
|
||||
* never reach the `cancelled` guard they exist to pin.
|
||||
*/
|
||||
const settleAndFlush = (fire: () => void) =>
|
||||
act(async () => {
|
||||
fire()
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
})
|
||||
|
||||
const spanOf = (call: unknown[]) => ({ from: call[0] as string, to: call[1] as string })
|
||||
const signalOf = (call: unknown[]) => call[2] as AbortSignal
|
||||
|
||||
const render = (initialProps: { dates: Set<string>; enabled: boolean }) =>
|
||||
renderHook(({ dates, enabled }) => useDawarichJournalTrail(dates, enabled), { initialProps })
|
||||
|
||||
beforeEach(() => {
|
||||
windowTrack.mockReset().mockResolvedValue(track())
|
||||
offline.mockReset().mockReturnValue(false)
|
||||
useAddonStore.setState({
|
||||
addons: [{ id: 'dawarich', name: 'Dawarich', type: 'integration', icon: 'Route', enabled: true }],
|
||||
loaded: true,
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDawarichJournalTrail', () => {
|
||||
it('FE-DAWARICH-JTRAIL-001: asks nothing on an instance where the addon is switched off', () => {
|
||||
useAddonStore.setState({ addons: [] })
|
||||
|
||||
const set = journalDates(DAY_ONE, DAY_TWO)
|
||||
const { result, rerender } = render({ dates: set, enabled: true })
|
||||
|
||||
// The addon being off is an instance-wide "do not talk to Dawarich". A
|
||||
// journal that fetched anyway would keep hitting a server the admin has
|
||||
// disconnected, and nothing on screen would show it.
|
||||
expect(windowTrack).not.toHaveBeenCalled()
|
||||
expect(result.current.status).toBe('idle')
|
||||
expect(result.current.tracks).toHaveLength(0)
|
||||
expect(result.current.fetchedAt).toBeNull()
|
||||
|
||||
// The empty result is one shared array, not a fresh literal per pass: the
|
||||
// journey map memoises on `tracks`, so a new identity every render would
|
||||
// rebuild every polyline on the map for nothing.
|
||||
const first = result.current.tracks
|
||||
rerender({ dates: set, enabled: false })
|
||||
expect(result.current.tracks).toBe(first)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-002: asks nothing while the journal has its track layer switched off', async () => {
|
||||
const set = journalDates(DAY_ONE, DAY_TWO)
|
||||
const { result, rerender } = render({ dates: set, enabled: false })
|
||||
|
||||
// `show_trip_tracks` gates the REQUEST, not just the drawing. Fetching and
|
||||
// then hiding would send the journal's whole date range to Dawarich on
|
||||
// behalf of somebody who asked for no tracks at all.
|
||||
expect(windowTrack).not.toHaveBeenCalled()
|
||||
expect(result.current.status).toBe('idle')
|
||||
|
||||
rerender({ dates: set, enabled: true })
|
||||
await waitFor(() => expect(windowTrack).toHaveBeenCalledTimes(1))
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-003: a journal with no dated trips has no window to ask about', () => {
|
||||
// Entries whose trips carry no start/end date contribute nothing to the
|
||||
// set. With an empty set there are no bounds to build a window from, and
|
||||
// sending one anyway would mean sending `undefined` as a timestamp.
|
||||
const { result } = render({ dates: journalDates(), enabled: true })
|
||||
|
||||
expect(windowTrack).not.toHaveBeenCalled()
|
||||
expect(result.current.status).toBe('idle')
|
||||
expect(result.current.tracks).toHaveLength(0)
|
||||
expect(result.current.fetchedAt).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-004: spans earliest to latest day whatever order the dates arrived in', async () => {
|
||||
// The dates come out of several trips in whatever order those trips are
|
||||
// listed, so the set is deliberately built back to front here. Trusting
|
||||
// insertion order would fetch the 5th to the 3rd: a backwards window, which
|
||||
// comes back empty rather than failing.
|
||||
const { result } = render({ dates: journalDates(DAY_THREE, DAY_ONE, DAY_TWO), enabled: true })
|
||||
|
||||
expect(result.current.status).toBe('loading')
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
// Whole-day bounds in UTC: a window that started at the moment of the fetch
|
||||
// would silently drop the morning of the first day.
|
||||
expect(spanOf(windowTrack.mock.calls[0])).toEqual({
|
||||
from: `${DAY_ONE}T00:00:00Z`,
|
||||
to: `${DAY_THREE}T23:59:59Z`,
|
||||
})
|
||||
expect(signalOf(windowTrack.mock.calls[0])).toBeInstanceOf(AbortSignal)
|
||||
expect(signalOf(windowTrack.mock.calls[0]).aborted).toBe(false)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-005: turns each drawable segment into one journey track the map cannot confuse with a place', async () => {
|
||||
windowTrack.mockResolvedValue(track({
|
||||
days: [
|
||||
{
|
||||
date: DAY_ONE,
|
||||
segments: [
|
||||
segment([[53.5, 10.0], [53.6, 10.1]]),
|
||||
// A single fix is not a line. It has to disappear here rather than
|
||||
// reach the renderer, which would draw a zero-length polyline.
|
||||
segment([[53.7, 10.2]]),
|
||||
],
|
||||
},
|
||||
day(DAY_TWO, [[48.1, 11.5], [48.2, 11.6], [48.3, 11.7]]),
|
||||
],
|
||||
pointCount: 6,
|
||||
}))
|
||||
|
||||
const { result } = render({ dates: journalDates(DAY_ONE, DAY_TWO), enabled: true })
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
expect(result.current.tracks).toEqual([
|
||||
{
|
||||
place_id: -1,
|
||||
trip_id: 0,
|
||||
name: DAY_ONE,
|
||||
color: DAWARICH_DAY_COLORS[0],
|
||||
points: [[53.5, 10.0], [53.6, 10.1]],
|
||||
},
|
||||
{
|
||||
place_id: -2,
|
||||
trip_id: 0,
|
||||
name: DAY_TWO,
|
||||
// Per-day hues, so "we were here on Tuesday" is readable; a second day
|
||||
// in the first day's colour would read as one continuous recording.
|
||||
color: DAWARICH_DAY_COLORS[1],
|
||||
points: [[48.1, 11.5], [48.2, 11.6], [48.3, 11.7]],
|
||||
},
|
||||
])
|
||||
// The journey map keys its polylines on place_id. Real places are positive,
|
||||
// so negative-and-distinct is what keeps a recorded line from evicting the
|
||||
// GPX track of an actual place.
|
||||
const ids = result.current.tracks.map(t => t.place_id)
|
||||
expect(ids.every(id => id < 0)).toBe(true)
|
||||
expect(new Set(ids).size).toBe(ids.length)
|
||||
|
||||
expect(result.current.fetchedAt).toBe(FETCHED_AT)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-006: a window with nothing recorded is an answer, not a failure', async () => {
|
||||
// Somebody who was not carrying a phone that week gets an empty track back,
|
||||
// and that is a perfectly good reply. Treating it as unavailable would
|
||||
// accuse their Dawarich instance of being broken.
|
||||
windowTrack.mockResolvedValue(track({ days: [] }))
|
||||
|
||||
const { result } = render({ dates: journalDates(DAY_ONE), enabled: true })
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
expect(result.current.tracks).toHaveLength(0)
|
||||
expect(result.current.fetchedAt).toBe(FETCHED_AT)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-007: an instance that does not answer leaves the journal without a line and says so', async () => {
|
||||
// Anything the repo throws lands here: a 502 from the proxy, a body that
|
||||
// does not parse against the shared schema, a missing API key. None of them
|
||||
// is the journal's fault and none may leave a half-drawn route.
|
||||
windowTrack.mockRejectedValue(new Error('502 from the Dawarich instance'))
|
||||
|
||||
const { result } = render({ dates: journalDates(DAY_ONE, DAY_TWO), enabled: true })
|
||||
await waitFor(() => expect(result.current.status).toBe('unavailable'))
|
||||
|
||||
expect(result.current.tracks).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-008: a connection that dies mid-flight is reported as offline, not as a broken instance', async () => {
|
||||
// The device is online when the request leaves and gone by the time it
|
||||
// fails. The flag is flipped while the request is held in the air, rather
|
||||
// than queued per call, so the case says what it means and does not depend
|
||||
// on how many times the hook happens to consult it. Blaming the instance
|
||||
// here would send the user reading server logs over a dropped wifi.
|
||||
const inFlight = held()
|
||||
windowTrack.mockImplementationOnce(() => inFlight.promise)
|
||||
|
||||
const { result } = render({ dates: journalDates(DAY_ONE), enabled: true })
|
||||
expect(result.current.status).toBe('loading')
|
||||
|
||||
offline.mockReturnValue(true)
|
||||
await settleAndFlush(() => inFlight.fail(new Error('network error')))
|
||||
|
||||
expect(result.current.status).toBe('offline')
|
||||
expect(windowTrack).toHaveBeenCalledTimes(1)
|
||||
expect(result.current.tracks).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-009: a device already offline is not made to wait for a timeout', () => {
|
||||
// `isEffectivelyOffline()` includes the manual switch, so this is also the
|
||||
// person who turned offline mode on before a flight. Firing the request
|
||||
// anyway would block the journal map until the request timed out, for an
|
||||
// answer that cannot arrive.
|
||||
offline.mockReturnValue(true)
|
||||
|
||||
const { result } = render({ dates: journalDates(DAY_ONE, DAY_THREE), enabled: true })
|
||||
|
||||
expect(windowTrack).not.toHaveBeenCalled()
|
||||
expect(result.current.status).toBe('offline')
|
||||
expect(result.current.tracks).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-010: a journal whose dates change abandons the answer to the old span', async () => {
|
||||
const first = held()
|
||||
windowTrack.mockImplementationOnce(() => first.promise)
|
||||
|
||||
const { result, rerender } = render({ dates: journalDates(DAY_ONE), enabled: true })
|
||||
expect(result.current.status).toBe('loading')
|
||||
|
||||
windowTrack.mockResolvedValueOnce(track({ days: [day(DAY_THREE)] }))
|
||||
rerender({ dates: journalDates(DAY_THREE), enabled: true })
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
expect(spanOf(windowTrack.mock.calls[1]).from).toBe(`${DAY_THREE}T00:00:00Z`)
|
||||
// The first request is cancelled at the wire, not merely ignored: a journal
|
||||
// being edited would otherwise pile up requests against somebody's own
|
||||
// server, each one a full location-history query.
|
||||
expect(signalOf(windowTrack.mock.calls[0]).aborted).toBe(true)
|
||||
|
||||
// The abandoned request answers late, the way a slow one does. Landing it
|
||||
// now would draw the old span's route under the new dates.
|
||||
await settleAndFlush(() => first.settle(track({ days: [day(DAY_ONE)] })))
|
||||
|
||||
expect(result.current.tracks.map(t => t.name)).toEqual([DAY_THREE])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-011: an answer that arrives after the layer was switched off is dropped', async () => {
|
||||
const pending = held()
|
||||
windowTrack.mockImplementationOnce(() => pending.promise)
|
||||
|
||||
const set = journalDates(DAY_ONE)
|
||||
const { result, rerender } = render({ dates: set, enabled: true })
|
||||
expect(result.current.status).toBe('loading')
|
||||
|
||||
rerender({ dates: set, enabled: false })
|
||||
expect(result.current.status).toBe('idle')
|
||||
|
||||
// Switching the layer off is an instruction about the map, and a request
|
||||
// that was already in the air must not undo it a second later.
|
||||
await settleAndFlush(() => pending.settle(track({ days: [day(DAY_ONE)] })))
|
||||
|
||||
expect(result.current.status).toBe('idle')
|
||||
expect(result.current.tracks).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-012: a failure that arrives after the layer was switched off stays silent', async () => {
|
||||
const pending = held()
|
||||
windowTrack.mockImplementationOnce(() => pending.promise)
|
||||
|
||||
const set = journalDates(DAY_ONE, DAY_TWO)
|
||||
const { result, rerender } = render({ dates: set, enabled: true })
|
||||
expect(result.current.status).toBe('loading')
|
||||
|
||||
rerender({ dates: set, enabled: false })
|
||||
|
||||
// The mirror of the case above: a late failure would put the layer into
|
||||
// `unavailable` while it is switched off, which is a complaint about a
|
||||
// request nobody is waiting for any more.
|
||||
await settleAndFlush(() => pending.fail(new Error('too late to matter')))
|
||||
|
||||
expect(result.current.status).toBe('idle')
|
||||
expect(result.current.tracks).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-JTRAIL-013: a route already drawn leaves the map with the switch, and is asked for again when it comes back', async () => {
|
||||
windowTrack.mockResolvedValue(track({ days: [day(DAY_ONE)], pointCount: 2 }))
|
||||
|
||||
const set = journalDates(DAY_ONE, DAY_TWO)
|
||||
const { result, rerender } = render({ dates: set, enabled: true })
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
expect(result.current.tracks).toHaveLength(1)
|
||||
|
||||
// Switching off has to withdraw the line that is already on screen, not
|
||||
// merely stop the next fetch: a hook that kept handing out the last answer
|
||||
// would leave somebody's recorded route drawn over a journal that asked for
|
||||
// it to be hidden, and nothing would clear it until the page was reloaded.
|
||||
rerender({ dates: set, enabled: false })
|
||||
expect(result.current.status).toBe('idle')
|
||||
expect(result.current.tracks).toHaveLength(0)
|
||||
|
||||
rerender({ dates: set, enabled: true })
|
||||
expect(result.current.status).toBe('loading')
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
// Asked again rather than replayed. Nothing here is cached by design, and
|
||||
// the recording may well have grown while the layer was off.
|
||||
expect(windowTrack).toHaveBeenCalledTimes(2)
|
||||
expect(result.current.tracks).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,513 @@
|
||||
/**
|
||||
* FE-DAWARICH-SUGG-001 to FE-DAWARICH-SUGG-019: the review list both Dawarich
|
||||
* shells read from.
|
||||
*
|
||||
* This hook is the only place the integration's review logic lives: the planner
|
||||
* panel and the journal sheet both call it, so a regression here is a
|
||||
* regression in both at once, and the two shells disagreeing about what is
|
||||
* still pending is precisely what it was written to prevent.
|
||||
*
|
||||
* Four things are worth pinning, and the cases below are grouped around them.
|
||||
*
|
||||
* - **The status ladder.** `idle` / `loading` / `ready` / `disconnected` /
|
||||
* `offline` / `unavailable` are not decoration: the panel renders nothing at
|
||||
* all on `idle`, so an instance without the addon has to produce `idle` and
|
||||
* no request, and a read that failed must not collapse into the same value
|
||||
* as "connected and quiet".
|
||||
* - **The stale-response guard.** Every read carries a `cancelled` flag. Lose
|
||||
* it and the answer to the trip the reader just left overwrites the list for
|
||||
* the trip they are looking at now, which reads as rows appearing from
|
||||
* nowhere.
|
||||
* - **In-place updates.** Accepting or dismissing replaces the one row and
|
||||
* never refetches, deliberately: a refetch reorders under the cursor, and
|
||||
* somebody working down a backlog loses their place on every press.
|
||||
* - **The message chain.** The server ships a reason code beside its English
|
||||
* prose so a non-English install never gets English. The code wins when this
|
||||
* build has a string for it, the prose is the fallback for a code it does
|
||||
* not know, and a generic sentence is the last resort. Each step is a branch,
|
||||
* and each of them is a sentence a real person reads.
|
||||
*
|
||||
* The repo and the API are mocked, the way the neighbouring
|
||||
* `DawarichAtlasDialog` test does it. Connectivity is not: `setForcedOffline`
|
||||
* drives the real `networkMode`, which is the single source of truth the hook
|
||||
* gates its writes on, and translation is the real provider, because the two
|
||||
* helpers at the bottom of the source depend on `t()` returning the key
|
||||
* untouched for a string this build does not have.
|
||||
*/
|
||||
import { createElement, type ReactNode } from 'react'
|
||||
import { act, renderHook, waitFor } from '@testing-library/react'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import type { DawarichAccept, DawarichAcceptResult, DawarichSuggestion, DawarichSuggestionList } from '@trek/shared'
|
||||
import { TranslationProvider } from '../i18n/TranslationContext'
|
||||
import { useAddonStore } from '../store/addonStore'
|
||||
import { setForcedOffline } from '../sync/networkMode'
|
||||
import { DawarichOfflineError } from '../repo/dawarichRepo'
|
||||
import { useDawarichSuggestions } from './useDawarichSuggestions'
|
||||
|
||||
const toast = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }
|
||||
vi.mock('../components/shared/Toast', () => ({ useToast: () => toast, default: () => toast }))
|
||||
|
||||
const repo = { suggestions: vi.fn() }
|
||||
vi.mock('../repo/dawarichRepo', () => {
|
||||
// The hook branches on `err instanceof DawarichOfflineError`, so the class the
|
||||
// test throws has to be the very one the hook imported. Defined inside the
|
||||
// factory and read back through the mocked module, it is.
|
||||
class DawarichOfflineError extends Error {}
|
||||
return {
|
||||
dawarichRepo: { suggestions: (...args: unknown[]) => repo.suggestions(...args) },
|
||||
DawarichOfflineError,
|
||||
}
|
||||
})
|
||||
|
||||
const api = { accept: vi.fn(), setState: vi.fn() }
|
||||
vi.mock('../api/dawarich', () => ({
|
||||
dawarichApi: {
|
||||
accept: (...args: unknown[]) => api.accept(...args),
|
||||
setState: (...args: unknown[]) => api.setState(...args),
|
||||
},
|
||||
}))
|
||||
|
||||
const ADDON = { id: 'dawarich', name: 'Dawarich', type: 'integration', icon: 'route', enabled: true }
|
||||
|
||||
/**
|
||||
* One recorded stay. Only a handful of these fields matter to this hook (id,
|
||||
* state and target), but the contract demands all of them, and a partial cast
|
||||
* would hide the day a required field is added.
|
||||
*/
|
||||
function stay(over: Partial<DawarichSuggestion> & { id: number }): DawarichSuggestion {
|
||||
return {
|
||||
id: over.id,
|
||||
sourceVisitId: String(over.id),
|
||||
tripId: null,
|
||||
tripTitle: null,
|
||||
name: `Stay ${over.id}`,
|
||||
lat: 50.94,
|
||||
lng: 6.96,
|
||||
startedAt: '2026-09-10T10:15:00+02:00',
|
||||
endedAt: '2026-09-10T12:40:00+02:00',
|
||||
durationMinutes: 145,
|
||||
localDate: '2026-09-10',
|
||||
sourceStatus: 'suggested',
|
||||
confidence: null,
|
||||
confidenceBand: null,
|
||||
state: 'new',
|
||||
target: null,
|
||||
acceptedPlaceId: null,
|
||||
acceptedJournalEntryId: null,
|
||||
acceptedBucketListItemId: null,
|
||||
sourceChanged: false,
|
||||
sourceMissing: false,
|
||||
matchedBucketListItemId: null,
|
||||
matchedBucketListName: null,
|
||||
countryCode: null,
|
||||
firstSeenAt: '2026-09-10T06:00:00Z',
|
||||
lastSeenAt: '2026-09-10T06:00:00Z',
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
/** Two rows, because "replaced in place" is only provable against a neighbour. */
|
||||
function list(over: Partial<DawarichSuggestionList> = {}): DawarichSuggestionList {
|
||||
return {
|
||||
suggestions: [stay({ id: 1 }), stay({ id: 2 })],
|
||||
connected: true,
|
||||
lastSyncAt: '2026-09-12T06:00:00Z',
|
||||
lastSyncState: 'ok',
|
||||
lastSyncError: null,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function acceptResult(suggestion: DawarichSuggestion): DawarichAcceptResult {
|
||||
return {
|
||||
suggestion,
|
||||
createdPlaceId: suggestion.acceptedPlaceId,
|
||||
createdJournalEntryId: suggestion.acceptedJournalEntryId,
|
||||
bucketListItemId: null,
|
||||
}
|
||||
}
|
||||
|
||||
/** A promise this test controls the settling of, to pin down state mid-flight. */
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void
|
||||
let reject!: (reason: unknown) => void
|
||||
const promise = new Promise<T>((res, rej) => {
|
||||
resolve = res
|
||||
reject = rej
|
||||
})
|
||||
return { promise, resolve, reject }
|
||||
}
|
||||
|
||||
type Filter = Parameters<typeof useDawarichSuggestions>[0]
|
||||
|
||||
const wrapper = ({ children }: { children: ReactNode }) => createElement(TranslationProvider, null, children)
|
||||
|
||||
function mount(filter?: Filter) {
|
||||
return renderHook((props: Filter) => useDawarichSuggestions(props), { wrapper, initialProps: filter })
|
||||
}
|
||||
|
||||
const PLACE_BODY: DawarichAccept = { target: 'place', tripId: 7, dayId: 3 }
|
||||
|
||||
// The shipped English for the keys the hook reaches for. Written out rather than
|
||||
// read back from the bundle so a reader of this file sees the sentence that ends
|
||||
// up on screen, and so a reworded string is a decision somebody makes here too.
|
||||
const EN = {
|
||||
offline: 'This needs a connection — TREK is offline right now.',
|
||||
unauthorized: 'Dawarich rejected the API key.',
|
||||
unknown: 'Something went wrong talking to Dawarich.',
|
||||
acceptError: 'Could not add this',
|
||||
updateError: 'Could not update this suggestion',
|
||||
acceptedPlace: 'Added to the trip',
|
||||
acceptedJournal: 'Added to the journal',
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
useAddonStore.setState({ addons: [ADDON], loaded: true })
|
||||
setForcedOffline(false)
|
||||
repo.suggestions.mockReset().mockResolvedValue(list())
|
||||
api.accept.mockReset()
|
||||
api.setState.mockReset()
|
||||
toast.success.mockReset()
|
||||
toast.error.mockReset()
|
||||
})
|
||||
|
||||
// The force-offline flag is module state, not component state: left on, it would
|
||||
// leak into the next file's writes.
|
||||
afterEach(() => setForcedOffline(false))
|
||||
|
||||
describe('useDawarichSuggestions', () => {
|
||||
it('FE-DAWARICH-SUGG-001: an instance without the addon asks nothing and reports idle', () => {
|
||||
useAddonStore.setState({ addons: [{ ...ADDON, enabled: false }] })
|
||||
|
||||
const { result } = mount()
|
||||
|
||||
// `idle` is what the panel keys "render nothing at all" off, so the empty
|
||||
// defaults underneath it matter as much as the status itself.
|
||||
expect(result.current.status).toBe('idle')
|
||||
expect(repo.suggestions).not.toHaveBeenCalled()
|
||||
expect(result.current.suggestions).toEqual([])
|
||||
expect(result.current.lastSyncState).toBe('never')
|
||||
expect(result.current.lastSyncError).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-002: the enabled addon reads with the filter it was handed and reports the sync', async () => {
|
||||
const read = deferred<DawarichSuggestionList>()
|
||||
repo.suggestions.mockReturnValueOnce(read.promise)
|
||||
|
||||
const { result } = mount({ tripId: 7, state: 'new' })
|
||||
|
||||
expect(result.current.status).toBe('loading')
|
||||
await act(async () => read.resolve(list()))
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
expect(repo.suggestions).toHaveBeenCalledWith({ tripId: 7, state: 'new' })
|
||||
expect(result.current.suggestions.map(s => s.id)).toEqual([1, 2])
|
||||
expect(result.current.lastSyncAt).toBe('2026-09-12T06:00:00Z')
|
||||
expect(result.current.lastSyncState).toBe('ok')
|
||||
expect(result.current.lastSyncError).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-003: a list from an instance nobody is connected to still shows its rows', async () => {
|
||||
// The suggestions survive a disconnect: they are TREK's own rows by then,
|
||||
// and hiding them would lose a backlog somebody still has to work through.
|
||||
repo.suggestions.mockResolvedValue(list({ connected: false, lastSyncState: 'never', lastSyncAt: null }))
|
||||
|
||||
const { result } = mount()
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('disconnected'))
|
||||
expect(result.current.suggestions).toHaveLength(2)
|
||||
expect(result.current.lastSyncAt).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-004: a read refused for being offline says offline, and says it quietly', async () => {
|
||||
repo.suggestions.mockRejectedValue(new DawarichOfflineError())
|
||||
|
||||
const { result } = mount()
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('offline'))
|
||||
// No toast: a read that could not run is a state the panel renders, not an
|
||||
// incident to interrupt somebody with.
|
||||
expect(toast.error).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-005: any other failure is unavailable, kept apart from offline', async () => {
|
||||
repo.suggestions.mockRejectedValue({ response: { data: { code: 'unreachable' } } })
|
||||
|
||||
const { result } = mount()
|
||||
|
||||
await waitFor(() => expect(result.current.status).toBe('unavailable'))
|
||||
expect(result.current.suggestions).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-006: reload re-reads with the same (absent) filter and takes the new answer', async () => {
|
||||
repo.suggestions
|
||||
.mockResolvedValueOnce(list())
|
||||
.mockResolvedValueOnce(list({ suggestions: [stay({ id: 3 })] }))
|
||||
|
||||
const { result } = mount()
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
act(() => result.current.reload())
|
||||
|
||||
await waitFor(() => expect(result.current.suggestions.map(s => s.id)).toEqual([3]))
|
||||
expect(repo.suggestions).toHaveBeenCalledTimes(2)
|
||||
expect(repo.suggestions).toHaveBeenLastCalledWith({ tripId: undefined, state: undefined })
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-007: a changed filter re-reads, an equal one does not', async () => {
|
||||
const { result, rerender } = mount({ tripId: 7 })
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
rerender({ tripId: 9, state: 'dismissed' })
|
||||
await waitFor(() => expect(repo.suggestions).toHaveBeenLastCalledWith({ tripId: 9, state: 'dismissed' }))
|
||||
// The request is fired synchronously by the effect, so the assertion above
|
||||
// can pass while the answer is still in the air. Let it land first: what the
|
||||
// next render must not do is start a third read, and that is only a clean
|
||||
// statement once the second one is finished.
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
// A fresh object carrying the same two values. The effect depends on the
|
||||
// unpacked primitives precisely so this does not fire a second request.
|
||||
// Every caller builds its filter object inline on every render.
|
||||
rerender({ tripId: 9, state: 'dismissed' })
|
||||
expect(repo.suggestions).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-008: the answer to the previous filter never overwrites the current list', async () => {
|
||||
const first = deferred<DawarichSuggestionList>()
|
||||
const second = deferred<DawarichSuggestionList>()
|
||||
repo.suggestions.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise)
|
||||
|
||||
const { result, rerender } = mount({ tripId: 7 })
|
||||
rerender({ tripId: 8 })
|
||||
|
||||
await act(async () => second.resolve(list({ suggestions: [stay({ id: 8 })] })))
|
||||
await waitFor(() => expect(result.current.suggestions.map(s => s.id)).toEqual([8]))
|
||||
|
||||
// The slow trip-7 read lands last. Without the cancelled flag the reader
|
||||
// would now be looking at another trip's stays under trip 8's heading.
|
||||
await act(async () => first.resolve(list({ suggestions: [stay({ id: 7 })] })))
|
||||
expect(result.current.suggestions.map(s => s.id)).toEqual([8])
|
||||
expect(result.current.status).toBe('ready')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-009: a read that fails after the panel closed changes nothing', async () => {
|
||||
const read = deferred<DawarichSuggestionList>()
|
||||
repo.suggestions.mockReturnValueOnce(read.promise)
|
||||
|
||||
const { result, unmount } = mount()
|
||||
expect(result.current.status).toBe('loading')
|
||||
unmount()
|
||||
|
||||
await act(async () => read.reject(new DawarichOfflineError()))
|
||||
|
||||
// The last value the hook ever rendered, untouched by the late rejection.
|
||||
expect(result.current.status).toBe('loading')
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-010: accepting while offline is refused before the request, not after a timeout', async () => {
|
||||
const { result } = mount()
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
// The reader flips the offline switch while the list is on screen. Reads go
|
||||
// through the repo, which knows; this write does not, so the hook says so.
|
||||
setForcedOffline(true)
|
||||
let ok: boolean | undefined
|
||||
await act(async () => {
|
||||
ok = await result.current.accept(1, PLACE_BODY)
|
||||
})
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(api.accept).not.toHaveBeenCalled()
|
||||
expect(toast.error).toHaveBeenCalledWith(EN.offline)
|
||||
expect(result.current.busyId).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-011: accepting marks the row busy, replaces only that row, and never refetches', async () => {
|
||||
const settled = deferred<DawarichAcceptResult>()
|
||||
api.accept.mockReturnValueOnce(settled.promise)
|
||||
const accepted = stay({ id: 1, state: 'accepted', target: 'place', acceptedPlaceId: 41 })
|
||||
|
||||
const { result } = mount()
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
let pending!: Promise<boolean>
|
||||
act(() => {
|
||||
pending = result.current.accept(1, PLACE_BODY)
|
||||
})
|
||||
// The row is disabled while its write is in the air; only that row.
|
||||
expect(result.current.busyId).toBe(1)
|
||||
|
||||
await act(async () => settled.resolve(acceptResult(accepted)))
|
||||
|
||||
await expect(pending).resolves.toBe(true)
|
||||
expect(api.accept).toHaveBeenCalledWith(1, PLACE_BODY)
|
||||
expect(result.current.suggestions[0]).toEqual(accepted)
|
||||
expect(result.current.suggestions[1]).toEqual(stay({ id: 2 }))
|
||||
expect(result.current.busyId).toBeNull()
|
||||
expect(toast.success).toHaveBeenCalledWith(EN.acceptedPlace)
|
||||
// One read, for the mount. A refetch here would reorder the list under the
|
||||
// cursor of somebody working down a backlog.
|
||||
expect(repo.suggestions).toHaveBeenCalledTimes(1)
|
||||
|
||||
// The target picks the sentence: a stay written into a journal must not be
|
||||
// reported as added to the trip.
|
||||
const journalled = stay({ id: 2, state: 'accepted', target: 'journal', acceptedJournalEntryId: 88 })
|
||||
api.accept.mockResolvedValueOnce(acceptResult(journalled))
|
||||
await act(async () => {
|
||||
await result.current.accept(2, { target: 'journal', journalId: 5 })
|
||||
})
|
||||
expect(toast.success).toHaveBeenLastCalledWith(EN.acceptedJournal)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-012: a failure carrying a known code is said in the language of the install', async () => {
|
||||
// The server sends both. The code wins, so a German install never gets the
|
||||
// English sentence sitting right beside it in the envelope.
|
||||
api.accept.mockRejectedValue({ response: { data: { code: 'unauthorized', error: 'Dawarich rejected the API key' } } })
|
||||
|
||||
const { result } = mount()
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
let ok: boolean | undefined
|
||||
await act(async () => {
|
||||
ok = await result.current.accept(1, PLACE_BODY)
|
||||
})
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(toast.error).toHaveBeenCalledWith(EN.unauthorized)
|
||||
// Nothing was written, so nothing in the list may look as if it had been.
|
||||
expect(result.current.suggestions[0].state).toBe('new')
|
||||
expect(result.current.busyId).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-013: an unknown code falls back to the server prose, and no envelope to the generic sentence', async () => {
|
||||
// A code from a server newer than this build: the prose beside it is the
|
||||
// only thing left that describes what actually happened.
|
||||
api.accept.mockRejectedValueOnce({ response: { data: { code: 'meteor_strike', error: 'Dawarich fell over' } } })
|
||||
|
||||
const { result } = mount()
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
await act(async () => {
|
||||
await result.current.accept(1, PLACE_BODY)
|
||||
})
|
||||
expect(toast.error).toHaveBeenCalledWith('Dawarich fell over')
|
||||
|
||||
// A transport-level failure carries no envelope at all.
|
||||
api.accept.mockRejectedValueOnce(new Error('Network Error'))
|
||||
await act(async () => {
|
||||
await result.current.accept(1, PLACE_BODY)
|
||||
})
|
||||
expect(toast.error).toHaveBeenLastCalledWith(EN.acceptError)
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-014: dismiss and restore move the one row between the two states', async () => {
|
||||
api.setState.mockImplementation(async (id: number, next: 'new' | 'dismissed') => stay({ id, state: next }))
|
||||
|
||||
const { result } = mount()
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
await act(async () => {
|
||||
await result.current.dismiss(2)
|
||||
})
|
||||
expect(api.setState).toHaveBeenCalledWith(2, 'dismissed')
|
||||
expect(result.current.suggestions.map(s => s.state)).toEqual(['new', 'dismissed'])
|
||||
|
||||
// Restoring is the same call with the other value. The panel offers it on
|
||||
// the handled rows, and it has to land on the same row it left.
|
||||
await act(async () => {
|
||||
await result.current.restore(2)
|
||||
})
|
||||
expect(api.setState).toHaveBeenLastCalledWith(2, 'new')
|
||||
expect(result.current.suggestions.map(s => s.state)).toEqual(['new', 'new'])
|
||||
expect(result.current.busyId).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-015: dismissing while offline is refused before the request too', async () => {
|
||||
const { result } = mount()
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
setForcedOffline(true)
|
||||
await act(async () => {
|
||||
await result.current.dismiss(1)
|
||||
})
|
||||
|
||||
expect(api.setState).not.toHaveBeenCalled()
|
||||
expect(toast.error).toHaveBeenCalledWith(EN.offline)
|
||||
expect(result.current.busyId).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-016: a state change that fails leaves the row alone and clears the busy flag', async () => {
|
||||
// An envelope with neither a code nor prose: a 500 through a proxy that
|
||||
// rewrote the body. The generic sentence is all that is left to say.
|
||||
api.setState.mockRejectedValue({ response: { data: {} } })
|
||||
|
||||
const { result } = mount()
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
await act(async () => {
|
||||
await result.current.dismiss(1)
|
||||
})
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(EN.updateError)
|
||||
expect(result.current.suggestions[0].state).toBe('new')
|
||||
// Cleared in `finally`: a row left busy after a failure can never be pressed
|
||||
// again, and the only way out would be a reload.
|
||||
expect(result.current.busyId).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-017: the last sync reason is translated, with a sentence for a code this build does not know', async () => {
|
||||
repo.suggestions.mockResolvedValue(list({ lastSyncState: 'failed', lastSyncError: 'unauthorized' }))
|
||||
const known = mount()
|
||||
await waitFor(() => expect(known.result.current.lastSyncError).toBe(EN.unauthorized))
|
||||
expect(known.result.current.lastSyncState).toBe('failed')
|
||||
known.unmount()
|
||||
|
||||
// A newer server reporting a reason this build has no string for. Showing
|
||||
// the bare code would put `dawarich.error.meteor_strike` on screen.
|
||||
repo.suggestions.mockResolvedValue(list({ lastSyncState: 'partial', lastSyncError: 'meteor_strike' }))
|
||||
const unfamiliar = mount()
|
||||
await waitFor(() => expect(unfamiliar.result.current.lastSyncError).toBe(EN.unknown))
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-018: a refused state change is said in the language of the install too', async () => {
|
||||
// Dismissing has its own error chain, and the code path through it is the
|
||||
// one somebody hits when the API key was revoked while the list sat open.
|
||||
// Only the generic fallback is exercised above, so without this the panel
|
||||
// could start answering half its failures in English and nothing would say so.
|
||||
api.setState.mockRejectedValue({
|
||||
response: { data: { code: 'unauthorized', error: 'Dawarich rejected the API key' } },
|
||||
})
|
||||
|
||||
const { result } = mount()
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
await act(async () => {
|
||||
await result.current.restore(1)
|
||||
})
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith(EN.unauthorized)
|
||||
expect(result.current.suggestions[0].state).toBe('new')
|
||||
expect(result.current.busyId).toBeNull()
|
||||
})
|
||||
|
||||
it('FE-DAWARICH-SUGG-019: a rejection carrying no reason at all still ends in a sentence and a false', async () => {
|
||||
// `Promise.reject()` with nothing in it is what an aborted request hands the
|
||||
// catch block. Reading `.response` off that unguarded throws inside the error
|
||||
// handler itself, and the dialog waiting on `accept` would then get a
|
||||
// rejected promise where it expects a plain `false` and stay open forever.
|
||||
api.accept.mockRejectedValueOnce(undefined)
|
||||
|
||||
const { result } = mount()
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
|
||||
let ok: boolean | undefined
|
||||
await act(async () => {
|
||||
ok = await result.current.accept(1, PLACE_BODY)
|
||||
})
|
||||
|
||||
expect(ok).toBe(false)
|
||||
expect(toast.error).toHaveBeenCalledWith(EN.acceptError)
|
||||
expect(result.current.busyId).toBeNull()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user