Files
faunosteo/apps/app/tests/unit/routes.trappingDraft.test.tsx
T
bchanot 9bd9acaf58 fix(app): rescue copy importable, trapping draft held, replace confirmed
The JSON rescue copy could not be restored in the app, a draft that traps
the engine left the tab on a reload screen and spent a recovery on every
read, and an unsaved or in-progress report could be lost by a reload
outside the editor or by New report / Import without warning.

Home import reads the copy (content-sniffed, 16 MiB cap, strict UTF-8)
through the core's draft.restore before any session change; a trapping
(draft, archive) pair is held in the resolution panel and only re-read
on Retry; ReplaceSessionDialog guards New report and Import; the
beforeunload guard is app-wide while unsaved. Supersedes BDR-055's
"never held" for `internal` only.
2026-10-17 12:58:57 +02:00

182 lines
7.0 KiB
TypeScript

/**
* A draft the engine traps on (R3 final checks): on a real poisoning runtime the editor
* shows the resolution panel (engine_failure row, engine notice), never the reload screen
* while the engine is not stopped; New report and Import answer the engine message then
* open the panel; the trapping (draft, archive) pair is read once (one trap across mount,
* New report, Import and remount); only the panel's Retry reads it again; a confirmed
* discard removes the draft and clears the memory.
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import EditorRoute from '@/app/routes/EditorRoute'
import HomeRoute from '@/app/routes/HomeRoute'
import NewReportRoute from '@/app/routes/NewReportRoute'
import { setCoreRuntime } from '@/core/runtime'
import { bundledSheetProvider } from '@/sheets/provider'
import { setSheetProvider } from '@/sheets/useSheet'
import { useReportStore } from '@/state/reportStore'
import { DRAFT_KEY, QUARANTINE_KEYS } from '@/state/persistence'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { testCoreRuntime, trappingCoreRuntime } from '../helpers/core'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
const MARKER = 'trap-me'
let sheet: SheetIndex
let draft: string
let traps: { count: number }
let engineStopped: () => boolean
let engineReady: () => Promise<boolean>
beforeAll(async () => {
sheet = await loadTestSheet()
draft = JSON.stringify(minimalReport(sheet, { conclusion: MARKER }))
})
beforeEach(async () => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
localStorage.clear()
sessionStorage.setItem('osteo:disclaimer-shown', '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
vi.stubGlobal('alert', vi.fn())
useReportStore.setState({ report: null, archive: null, activeObservationIndex: 0 })
useReportStore.getState().clearTrapped()
const trapping = await trappingCoreRuntime(MARKER)
traps = trapping.traps
engineStopped = () => trapping.runtime.stopped
engineReady = () => trapping.runtime.ready()
setCoreRuntime(trapping.runtime)
setSheetProvider(bundledSheetProvider)
// After the reset (an empty store mirrors no draft): the tab as a reload finds it.
sessionStorage.setItem(DRAFT_KEY, draft)
})
afterEach(async () => {
cleanup()
vi.unstubAllGlobals()
vi.restoreAllMocks()
useReportStore.getState().clearTrapped()
setCoreRuntime(await testCoreRuntime())
setSheetProvider(bundledSheetProvider)
})
const routes = (initial: string) =>
render(
<MemoryRouter initialEntries={[initial]}>
<Routes>
<Route path="/" element={<HomeRoute />} />
<Route path="/new" element={<NewReportRoute />} />
<Route path="/editor" element={<EditorRoute />} />
</Routes>
</MemoryRouter>,
)
async function expectEnginePanel() {
await screen.findByText(fr['session.held.notice_engine']!)
expect(screen.getByTestId('held-draft')).toHaveTextContent(
fr['session.held.draft_engine_failure']!.replace('{size}', /\d+ Ko/.exec(
screen.getByTestId('held-draft').textContent ?? '',
)![0]),
)
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
}
async function submitNewReport(user: ReturnType<typeof userEvent.setup>) {
await user.type(screen.getByLabelText(fr['form.practitioner.name']!), 'Dr X')
await user.type(screen.getByLabelText(fr['form.animal.name']!), 'Rex')
await user.type(screen.getByLabelText(fr['form.owner.name']!), 'Y')
const submit = screen.getByRole('button', { name: fr['new_report.submit']! })
await waitFor(() => expect(submit).toBeEnabled())
await user.click(submit)
await user.click(
await screen.findByRole('button', { name: fr['session.replace.confirm']! }),
)
}
async function pickCopy(user: ReturnType<typeof userEvent.setup>) {
const pick = screen.getByRole('button', { name: fr['home.import.cta']! })
await waitFor(() => expect(pick).toBeEnabled())
await user.click(pick)
vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => undefined)
await user.click(
await screen.findByRole('button', { name: fr['session.replace.confirm']! }),
)
const copy = JSON.stringify(minimalReport(sheet, { id: 'other' }))
fireEvent.change(document.querySelector('input[type="file"]')!, {
target: { files: [new File([copy], 'copie.json', { type: 'application/json' })] },
})
}
describe('a draft the engine traps on', () => {
it('opens the engine_failure panel, never the reload screen', async () => {
routes('/editor')
await expectEnginePanel()
expect(traps.count).toBe(1)
expect(engineStopped()).toBe(false)
expect(useReportStore.getState().report).toBeNull()
})
it('is read once across mount, New report, Import and remount', async () => {
const user = userEvent.setup()
routes('/editor')
await expectEnginePanel()
cleanup()
routes('/new')
await submitNewReport(user)
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked_engine']),
)
await expectEnginePanel()
cleanup()
routes('/')
await pickCopy(user)
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['session.held_blocked_engine']),
)
await expectEnginePanel()
cleanup()
routes('/editor')
await expectEnginePanel()
expect(traps.count).toBe(1)
expect(useReportStore.getState().report).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
})
it('reads the pair again only on the panel Retry', async () => {
const user = userEvent.setup()
routes('/editor')
await expectEnginePanel()
// The instance that trapped is replaced in the background: retry on the fresh one.
await engineReady()
await user.click(screen.getByRole('button', { name: fr['session.held.retry'] }))
await waitFor(() => expect(traps.count).toBe(2))
await expectEnginePanel()
})
it('removes only the draft after the confirmation and forgets the trap', async () => {
const user = userEvent.setup()
routes('/editor')
await expectEnginePanel()
await user.click(screen.getByRole('button', { name: fr['session.held.discard'] }))
expect(sessionStorage.getItem(DRAFT_KEY)).toBe(draft)
await user.click(
screen.getByRole('button', { name: fr['session.held.discard_confirm'] }),
)
expect(sessionStorage.getItem(DRAFT_KEY)).toBeNull()
expect(sessionStorage.getItem(QUARANTINE_KEYS.draft)).toBeNull()
cleanup()
await engineReady()
// The memory is gone: the same text, stored again, is read (and traps) anew.
sessionStorage.setItem(DRAFT_KEY, draft)
routes('/editor')
await expectEnginePanel()
expect(traps.count).toBe(2)
})
})