Files
faunosteo/apps/app/tests/unit/routes.coreStopped.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

272 lines
11 KiB
TypeScript

/**
* The engine stopped for good (three recoveries spent, owner decision 2026-10-15): the
* stopped notice on every core page, its two variants (tab copy saved: reload; tab storage
* full: download a copy), no retry anywhere, the editor's save banner with its copy button,
* and the stopped alerts (the beforeunload guard has its own hook test).
*/
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import EditorRoute from '@/app/routes/EditorRoute'
import HomeRoute from '@/app/routes/HomeRoute'
import NewReportRoute from '@/app/routes/NewReportRoute'
import CoreUnavailable from '@/components/report/CoreUnavailable'
import { coreRuntime } from '@/core/runtime'
import { exportReportToPdf } from '@/pdf/export'
import { readAttachment } from '@/pdf/import'
import { loadSheetIndex } from '@/sheets/useSheet'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import type { SheetIndex } from '@/services/sheetIndex'
import { controlStopped } from '../helpers/core'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
vi.mock('@/pdf/export', () => ({ exportReportToPdf: vi.fn() }))
vi.mock('@/pdf/import', async (importOriginal) => ({
...(await importOriginal<typeof import('@/pdf/import')>()),
readAttachment: vi.fn(),
}))
vi.mock('@/sheets/useSheet', async (importOriginal) => ({
...(await importOriginal<typeof import('@/sheets/useSheet')>()),
loadSheetIndex: vi.fn((await importOriginal<typeof import('@/sheets/useSheet')>()).loadSheetIndex),
}))
let sheet: SheetIndex
let setStopped: (next: boolean) => void
const blobs: Blob[] = []
beforeAll(async () => {
sheet = await loadTestSheet()
})
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.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().hydrateImport({ report: minimalReport(sheet), archive: null }, sheet)
setStopped = controlStopped(coreRuntime(), true)
blobs.length = 0
URL.createObjectURL = vi.fn((blob: Blob | MediaSource) => {
blobs.push(blob as Blob)
return 'blob:faunosteo-test'
})
URL.revokeObjectURL = vi.fn()
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined)
})
afterEach(() => {
setStopped(false)
cleanup()
vi.restoreAllMocks()
vi.unstubAllGlobals()
useReportStore.setState({ report: null, saveFailed: false })
})
/** The tab's storage is full from now on: the next change of the report is not saved. */
function fillStorage() {
vi.spyOn(sessionStorage, 'setItem').mockImplementation(() => {
throw new DOMException('full', 'QuotaExceededError')
})
act(() => useReportStore.getState().setConclusion('edited after the quota'))
expect(useReportStore.getState().saveFailed).toBe(true)
}
const retryButton = () => screen.queryByRole('button', { name: fr['sheet.core_retry'] })
const reloadButton = () => screen.queryByRole('button', { name: fr['core.reload'] })
const copyButton = () => screen.queryByRole('button', { name: fr['session.held.download'] })
function expectSavedVariant() {
expect(screen.getByText(fr['core.stopped']!)).toBeInTheDocument()
expect(reloadButton()).toBeInTheDocument()
expect(copyButton()).toBeNull()
expect(retryButton()).toBeNull()
}
async function expectUnsavedVariant() {
expect(screen.getByText(fr['core.stopped_unsaved']!)).toBeInTheDocument()
expect(reloadButton()).toBeNull()
expect(retryButton()).toBeNull()
await userEvent.setup().click(copyButton()!)
expect(blobs).toHaveLength(1)
expect(blobs[0]!.type).toBe('application/json')
expect(await blobs[0]!.text()).toBe(JSON.stringify(useReportStore.getState().report))
}
const inRouter = (node: React.ReactNode) =>
render(<MemoryRouter initialEntries={['/']}>{node}</MemoryRouter>)
describe('the stopped notice on the pages that run the core', () => {
it('Home, New report and the full-page notice: reload when the save is fine', async () => {
inRouter(<HomeRoute />)
expectSavedVariant()
cleanup()
inRouter(<NewReportRoute />)
expectSavedVariant()
cleanup()
render(<CoreUnavailable onRetry={() => undefined} />)
expectSavedVariant()
expect(screen.queryByText(fr['sheet.core_unavailable']!)).toBeNull()
})
it('Home, New report and the full-page notice: a copy of the in-memory report when storage is full', async () => {
fillStorage()
inRouter(<HomeRoute />)
await expectUnsavedVariant()
cleanup()
blobs.length = 0
inRouter(<NewReportRoute />)
await expectUnsavedVariant()
cleanup()
blobs.length = 0
render(<CoreUnavailable onRetry={() => undefined} />)
await expectUnsavedVariant()
})
it('is absent while the engine runs, and appears when it stops', async () => {
setStopped(false)
inRouter(<HomeRoute />)
expect(screen.queryByText(fr['core.stopped']!)).toBeNull()
act(() => setStopped(true))
await screen.findByText(fr['core.stopped']!)
})
it('keeps the full-page retry while the engine is not stopped', () => {
setStopped(false)
render(<CoreUnavailable onRetry={() => undefined} />)
expect(screen.getByText(fr['sheet.core_unavailable']!)).toBeInTheDocument()
expect(retryButton()).toBeInTheDocument()
})
})
describe('EditorRoute', () => {
const mountEditor = () => inRouter(<EditorRoute />)
it('puts the stopped notice in the banner slot, in place of the storage-full text', async () => {
mountEditor()
await screen.findByText(fr['core.stopped']!)
expectSavedVariant()
fillStorage()
await screen.findByText(fr['core.stopped_unsaved']!)
expect(screen.queryByText(fr['editor.save_failed']!)).toBeNull()
expect(screen.getAllByText(fr['core.stopped_unsaved']!)).toHaveLength(1)
await expectUnsavedVariant()
})
it('keeps the storage-full text and adds the copy button when the engine runs', async () => {
setStopped(false)
mountEditor()
await screen.findByTestId('sheet-status')
expect(screen.queryByText(fr['editor.save_failed']!)).toBeNull()
fillStorage()
await screen.findByText(fr['editor.save_failed']!)
expect(screen.queryByText(fr['core.stopped_unsaved']!)).toBeNull()
await userEvent.setup().click(copyButton()!)
expect(await blobs[0]!.text()).toBe(JSON.stringify(useReportStore.getState().report))
})
it('says the stopped text when the export fails once the engine stopped', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
vi.mocked(exportReportToPdf).mockRejectedValue(new Error('core_unavailable'))
mountEditor()
await userEvent.setup().click(await screen.findByRole('button', { name: fr['editor.export']! }))
await waitFor(() => expect(window.alert).toHaveBeenCalledWith(fr['core.stopped']))
})
it('says the unsaved stopped text for an export that fails with a full storage', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
vi.mocked(exportReportToPdf).mockRejectedValue(new Error('core_unavailable'))
mountEditor()
const button = await screen.findByRole('button', { name: fr['editor.export']! })
fillStorage()
await userEvent.setup().click(button)
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['core.stopped_unsaved']),
)
})
it('keeps the export message while the engine is not stopped', async () => {
setStopped(false)
vi.spyOn(console, 'error').mockImplementation(() => undefined)
vi.mocked(exportReportToPdf).mockRejectedValue(new Error('render exploded'))
mountEditor()
await userEvent.setup().click(await screen.findByRole('button', { name: fr['editor.export']! }))
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['editor.export_failed']),
)
})
})
describe('the stopped text on the Home import line and the New report alert', () => {
const realLoad = vi.mocked(loadSheetIndex).getMockImplementation()!
beforeEach(() => {
vi.mocked(loadSheetIndex).mockResolvedValue(null)
vi.mocked(readAttachment).mockResolvedValue({ version: 3 })
})
afterEach(() => vi.mocked(loadSheetIndex).mockImplementation(realLoad))
async function pickPdf() {
inRouter(<HomeRoute />)
const button = screen.getByRole('button', { name: fr['home.import.cta'] })
await waitFor(() => expect(button).toBeEnabled())
const file = new File([new Uint8Array([37, 80, 68, 70])], 'bilan.pdf')
fireEvent.change(document.querySelector('input[type="file"]')!, {
target: { files: [file] },
})
}
async function submitNewReport() {
const user = userEvent.setup()
inRouter(<NewReportRoute />)
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)
// A report is in progress (beforeEach): replacing it is confirmed first.
await user.click(await screen.findByRole('button', { name: fr['session.replace.confirm']! }))
}
it('Home import: the engine error line says the stopped text', async () => {
await pickPdf()
await screen.findByText(fr['core.stopped']!, { selector: 'p.text-red-700' })
expect(screen.queryByText(fr['home.import.error_core_unavailable']!)).toBeNull()
})
it('Home import: the unsaved stopped text when storage is full', async () => {
fillStorage()
await pickPdf()
await screen.findByText(fr['core.stopped_unsaved']!, { selector: 'p.text-red-700' })
})
it('Home import: keeps the engine error line while the engine is not stopped', async () => {
setStopped(false)
await pickPdf()
await screen.findByText(fr['home.import.error_core_unavailable']!)
})
it('New report: the alert says the stopped text', async () => {
await submitNewReport()
await waitFor(() => expect(window.alert).toHaveBeenCalledWith(fr['core.stopped']))
})
it('New report: the unsaved stopped text when storage is full', async () => {
fillStorage()
await submitNewReport()
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['core.stopped_unsaved']),
)
})
it('New report: keeps the sheet alert while the engine is not stopped', async () => {
setStopped(false)
await submitNewReport()
await waitFor(() =>
expect(window.alert).toHaveBeenCalledWith(fr['sheet.core_unavailable']),
)
})
})