Files
faunosteo/apps/app/tests/unit/routes.catalogue.test.tsx
T

745 lines
36 KiB
TypeScript

import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import type { PreviewState } from '@faunosteo/core-wasm/types'
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
import { bundledSheet } from '../helpers/sheet'
import { controlStopped } from '../helpers/core'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import CatalogRoute from '@/app/routes/app/anatomy/CatalogRoute'
import SheetRoute from '@/app/routes/app/anatomy/SheetRoute'
import { coreRuntime } from '@/core/runtime'
import { CataloguePreview } from '@/catalogue/preview'
import { cardFailure, coreFailure, serverFailure, type CatalogueFailure } from '@/catalogue/failure'
import { SheetFailure } from '@faunosteo/supabase'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import Icon, { type IconName } from '@/components/ui/Icon'
import { fr } from '@/i18n/fr'
import { en } from '@/i18n/en'
/**
* The catalogue screens (V1-2.5 slice I, boards 01 to 03) on a fake client and
* the real core: the equine draft stands for a published version, its
* drawing served as Storage would, so the core checks the hash, the
* fingerprint and the caps exactly as in the browser.
*/
const SHEET = '503dc301-0000-4000-8000-000000000001'
const OTHER = '503dc301-0000-4000-8000-000000000002'
const V1 = 'aaaaaaaa-0000-4000-8000-000000000001'
const V2 = 'aaaaaaaa-0000-4000-8000-000000000002'
const V3 = 'aaaaaaaa-0000-4000-8000-000000000003'
const DOG = 'bbbbbbbb-0000-4000-8000-000000000001'
let fake: FakeSupabase
let document: unknown
let assetId: string
let sha256: string
let bytes: Uint8Array<ArrayBuffer>
let fingerprint: string
beforeAll(async () => {
const bundle = await bundledSheet()
document = bundle.document
;[assetId] = Object.keys(bundle.assets)
sha256 = bundle.assetHashes[assetId]
bytes = new TextEncoder().encode(bundle.assets[assetId])
// The fingerprint a publication stores: the core's, read from a draft preview.
const draft = new CataloguePreview(
coreRuntime(),
{ status: 'draft', document: JSON.stringify(document) },
[{ assetId, sha256, bytes }],
)
const state = draft.state()
if (!state.ok || !state.value.fingerprint) throw new Error('draft preview refused')
fingerprint = state.value.fingerprint
draft.free()
})
function versionAnswer(id: string, status: 'published' | 'deprecated', patch: Record<string, unknown> = {}) {
return {
sheet_id: SHEET,
version_id: id,
version_number: Number(id.slice(-1)),
status,
species_id: 'equine',
document,
revision: 1,
// PreviewSheet requires the stored fingerprint for deprecated versions too, while
// `get_sheet_version` returns it for published ones only (gap reported at V1-2.5).
fingerprint,
drawings: [{ asset_id: assetId, sha256, byte_size: bytes.length }],
...patch,
}
}
/** `get_sheet_version` answers per id, as the server would; unknown ids are `not_found`. */
function serveVersions(answers: Record<string, unknown>) {
fake.rpcResults.get_sheet_version = () => {
const [, args] = fake.rpcCalls.filter(([n]) => n === 'get_sheet_version').at(-1)!
const answer = answers[(args as { version_id: string }).version_id]
return answer ? { data: answer } : { error: { message: 'not_found', code: '42501' } }
}
}
function mount(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/app/anatomy" element={<CatalogRoute />} />
<Route path="/app/anatomy/:sheetId" element={<SheetRoute />} />
<Route path="/app/anatomy/:sheetId/versions/:number" element={<SheetRoute />} />
</Routes>
</MemoryRouter>,
)
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
useAuthStore.setState({ status: 'signed_in', user: fakeUser(), profile: fakeProfile(), catalogGrants: [] })
fake = createFakeSupabase()
fake.tables.species = [
{ id: 'equine', name_fr: 'Cheval', name_en: 'Horse', sort_order: 1 },
{ id: 'canine', name_fr: 'Chien', name_en: 'Dog', sort_order: 2 },
]
fake.tables.anatomical_sheet_versions = [
{ sheet_id: SHEET, id: V3, version_number: 3, status: 'published', published_at: '2026-10-28T10:00:00Z', deprecated_at: null },
{ sheet_id: SHEET, id: V2, version_number: 2, status: 'deprecated', published_at: '2026-10-20T10:00:00Z', deprecated_at: '2026-10-28T10:00:00Z' },
{ sheet_id: SHEET, id: V1, version_number: 1, status: 'published', published_at: '2026-10-10T10:00:00Z', deprecated_at: null },
]
fake.rpcResults.list_official_catalog = {
data: [
{ sheet_id: SHEET, species_id: 'equine', slug: 'cheval', name: { fr: 'Cheval', en: 'Horse' }, description: {}, version_number: 3, version_id: V3 },
{ sheet_id: OTHER, species_id: 'canine', slug: 'chien', name: { fr: 'Chien, rachis', en: 'Dog spine' }, description: {}, version_number: 1, version_id: DOG },
],
}
serveVersions({ [V3]: versionAnswer(V3, 'published'), [V2]: versionAnswer(V2, 'deprecated'), [V1]: versionAnswer(V1, 'published') })
fake.storage.download.mockImplementation(async () => ({ data: new Blob([bytes]), error: null }))
mocks.fake = fake
})
afterEach(() => cleanup())
describe('/app/anatomy', () => {
it('shows each published sheet with its species, status, version line and link', async () => {
mount('/app/anatomy')
expect(await screen.findByRole('heading', { level: 1, name: fr['shell.nav.anatomy'] })).toBeInTheDocument()
const card = (await screen.findByRole('heading', { level: 2, name: 'Cheval' })).closest('article')!
expect(within(card).getByText(fr['catalogue.status.published'])).toBeInTheDocument()
expect(within(card).getByText('Cheval', { selector: 'span' })).toBeInTheDocument()
expect(
await within(card).findByText('Version 3 · publiée le 28/10/2026 · 2 vues, 27 zones de constats'),
).toBeInTheDocument()
// The thumbnail is the core's composed main view, as an image (never inserted as markup).
expect(card.querySelector('img')?.getAttribute('src')).toMatch(/^blob:/)
expect(within(card).getByRole('link', { name: 'Consulter Cheval' })).toHaveAttribute('href', `/app/anatomy/${SHEET}`)
// The card whose version cannot be read keeps its name, version and link.
const dog = screen.getByRole('heading', { level: 2, name: 'Chien, rachis' }).closest('article')!
expect(within(dog).getByText('Version 1')).toBeInTheDocument()
// Its refused read is said in the card (F7).
expect(await within(dog).findByText(fr['access_denied.title'])).toBeInTheDocument()
})
it('searches by sheet name in either language and filters by species', async () => {
mount('/app/anatomy')
await screen.findByRole('heading', { level: 2, name: 'Cheval' })
const search = screen.getByRole('searchbox', { name: fr['catalogue.search'] })
await userEvent.type(search, 'dog')
expect(screen.queryByRole('heading', { level: 2, name: 'Cheval' })).toBeNull()
expect(screen.getByRole('heading', { level: 2, name: 'Chien, rachis' })).toBeInTheDocument()
await userEvent.clear(search)
await userEvent.type(search, 'thoracique')
expect(screen.getByText(fr['catalogue.no_results'])).toBeInTheDocument()
await userEvent.clear(search)
const chips = screen.getByRole('group', { name: fr['catalogue.species_filter'] })
expect(within(chips).getAllByRole('button').map((b) => b.textContent)).toEqual([
fr['catalogue.all_species'],
'Cheval',
'Chien',
])
await userEvent.click(within(chips).getByRole('button', { name: 'Cheval' }))
expect(screen.getByRole('heading', { level: 2, name: 'Cheval' })).toBeInTheDocument()
expect(screen.queryByRole('heading', { level: 2, name: 'Chien, rachis' })).toBeNull()
})
it('says when no sheet is published', async () => {
fake.rpcResults.list_official_catalog = { data: [] }
mount('/app/anatomy')
expect(await screen.findByText(fr['catalogue.empty'])).toBeInTheDocument()
})
it('shows « Accès non autorisé » on the server refusal', async () => {
fake.rpcResults.list_official_catalog = { error: { message: 'rights.catalog', code: '42501' } }
mount('/app/anatomy')
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
})
it('names an unavailable server and reads again on retry', async () => {
fake.rpcResults.list_official_catalog = { error: { message: 'boom' } }
mount('/app/anatomy')
expect(await screen.findByText(fr['catalogue.failure.unavailable'])).toBeInTheDocument()
fake.rpcResults.list_official_catalog = { data: [] }
await userEvent.click(screen.getByRole('button', { name: fr['common.retry'] }))
expect(await screen.findByText(fr['catalogue.empty'])).toBeInTheDocument()
})
})
describe('/app/anatomy/:sheetId', () => {
it('shows the current version: views, zone panel, references and disclaimer', async () => {
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByRole('heading', { level: 1, name: 'Cheval' })).toBeInTheDocument()
expect(screen.getByText('Version 3 · publiée le 28/10/2026')).toBeInTheDocument()
const tabs = screen.getAllByRole('tab')
expect(tabs.map((tab) => tab.textContent)).toEqual(['Vue latérale gauche', 'Tête (vue latérale gauche)'])
expect(tabs[0]).toHaveAttribute('aria-selected', 'true')
const canvas = screen.getByTestId('catalogue-canvas-drawing')
await waitFor(() => expect(canvas.querySelector('svg')).not.toBeNull())
fireEvent.click(canvas.querySelector('[data-anno-id="thoracic"]')!)
expect(screen.getByRole('heading', { name: 'Zone : Vertèbres thoraciques' })).toBeInTheDocument()
expect(screen.getByText('Catégorie : Segments vertébraux · vertèbres T1 à T18')).toBeInTheDocument()
expect(screen.getByRole('heading', { level: 3, name: 'Dysfonctions ostéopathiques' })).toBeInTheDocument()
expect(canvas.querySelector('[data-anno-id="thoracic"]')).toHaveAttribute('data-state', 'current')
expect(screen.getByRole('heading', { name: fr['catalogue.references.title'] })).toBeInTheDocument()
expect(screen.getByText(/Code rural et de la pêche maritime, art\. L\. 243-3/)).toBeInTheDocument()
expect(screen.getByText(/Aucun diagnostic médical n'est posé/)).toBeInTheDocument()
// No capability: no link to the administration.
expect(screen.queryByRole('link', { name: fr['catalogue.open_admin'] })).toBeNull()
})
it('keeps the zone panel when the empty drawing is tapped (reader: no deselect)', async () => {
mount(`/app/anatomy/${SHEET}`)
const canvas = await screen.findByTestId('catalogue-canvas-drawing')
await waitFor(() => expect(canvas.querySelector('[data-anno-id="thoracic"]')).not.toBeNull())
fireEvent.click(canvas.querySelector('[data-anno-id="thoracic"]')!)
const empty = canvas.querySelector('svg')!
const init = { pointerId: 1, isPrimary: true, button: 0, pointerType: 'mouse' }
fireEvent.pointerDown(empty, init)
fireEvent.pointerUp(empty, init)
fireEvent.click(empty)
expect(screen.getByRole('heading', { name: 'Zone : Vertèbres thoraciques' })).toBeInTheDocument()
expect(canvas.querySelector('[data-anno-id="thoracic"]')).toHaveAttribute('data-state', 'current')
})
it('opens the detail view from its link on the drawing', async () => {
mount(`/app/anatomy/${SHEET}`)
const canvas = await screen.findByTestId('catalogue-canvas-drawing')
await waitFor(() => expect(canvas.querySelector('[data-anno-id="head-trigger"]')).not.toBeNull())
fireEvent.click(canvas.querySelector('[data-anno-id="head-trigger"]')!)
expect(screen.getByRole('tab', { name: 'Tête (vue latérale gauche)' })).toHaveAttribute('aria-selected', 'true')
})
it('lists the versions with the « Retirée » mark, each linking to its page', async () => {
mount(`/app/anatomy/${SHEET}`)
await userEvent.click(await screen.findByRole('button', { name: '2 versions antérieures' }))
const list = screen.getByRole('list', { name: fr['catalogue.versions.title'] })
const links = within(list).getAllByRole('link')
expect(links.map((l) => l.getAttribute('href'))).toEqual([3, 2, 1].map((n) => `/app/anatomy/${SHEET}/versions/${n}`))
expect(links[0]).toHaveAttribute('aria-current', 'page')
expect(within(links[1]).getByText(fr['catalogue.status.deprecated'])).toBeInTheDocument()
})
it('opens a retired version by number with its mark', async () => {
mount(`/app/anatomy/${SHEET}/versions/2`)
expect(await screen.findByText('Version 2 · publiée le 20/10/2026')).toBeInTheDocument()
expect(screen.getByText(fr['catalogue.status.deprecated'])).toBeInTheDocument()
expect(fake.rpcCalls.filter(([n]) => n === 'get_sheet_version').map(([, a]) => a)).toEqual([{ version_id: V2 }])
})
it('links an editor to the administration', async () => {
useAuthStore.setState({ catalogGrants: [{ kind: 'sheet_editor', expires_at: null, revoked_at: null }] })
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByRole('link', { name: fr['catalogue.open_admin'] })).toHaveAttribute(
'href',
`/app/admin/sheets/${SHEET}`,
)
})
it.each([
['an unknown sheet', `/app/anatomy/${OTHER}`],
['a malformed id', '/app/anatomy/not-a-uuid'],
['an unknown number', `/app/anatomy/${SHEET}/versions/9`],
['a malformed number', `/app/anatomy/${SHEET}/versions/0`],
])('shows « Accès non autorisé » for %s', async (_case, path) => {
mount(path)
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
})
it('shows « Accès non autorisé » when the version read is refused', async () => {
serveVersions({})
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
})
it('zooms with the buttons and « Ajuster » brings the whole drawing back', async () => {
mount(`/app/anatomy/${SHEET}`)
const drawing = await screen.findByTestId('catalogue-canvas-drawing')
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.in'] }))
expect(drawing.style.transform).toContain('scale(1.5)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.in'] }))
expect(drawing.style.transform).toContain('scale(2.25)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.out'] }))
expect(drawing.style.transform).toContain('scale(1.5)')
await userEvent.click(screen.getByRole('button', { name: fr['catalogue.zoom.fit'] }))
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
// The keyboard on the focused box: + zooms, 0 fits.
fireEvent.keyDown(screen.getByTestId('catalogue-canvas'), { key: '+' })
expect(drawing.style.transform).toContain('scale(1.5)')
fireEvent.keyDown(screen.getByTestId('catalogue-canvas'), { key: '0' })
expect(drawing.style.transform).toBe('translate(0px, 0px) scale(1)')
})
})
describe('failures', () => {
it.each([
[
'a drawing whose bytes do not hash to its row',
() => {
const altered = bytes.slice()
altered[200] ^= 1
fake.storage.download.mockImplementation(async () => ({ data: new Blob([altered]), error: null }))
},
'catalogue.failure.drawing_hash_mismatch',
],
[
'a stored fingerprint the core does not recompute',
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) }),
'catalogue.failure.fingerprint_mismatch',
],
[
'a drawing Storage does not give',
() =>
fake.storage.download.mockImplementation(async () => ({ data: null, error: { status: 400, name: 'StorageApiError' } })),
'catalogue.failure.drawing_missing',
],
[
'an unreadable document',
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { document: { schema_version: 2 } }) }),
'catalogue.failure.invalid_document',
],
])('names %s', async (_case, arrange, key) => {
arrange()
mount(`/app/anatomy/${SHEET}`)
expect(await screen.findByText(fr[key])).toBeInTheDocument()
expect(screen.getByRole('button', { name: fr['common.retry'] })).toBeInTheDocument()
})
it('folds server and core kinds into the closed page kinds', () => {
expect(serverFailure(new SheetFailure('rights.catalog'))).toBe('denied')
expect(serverFailure(new SheetFailure('not_found'))).toBe('denied')
expect(serverFailure(new SheetFailure('network'))).toBe('network')
expect(serverFailure(new SheetFailure('draft_conflict'))).toBe('unavailable')
expect(coreFailure('caps')).toBe('caps')
expect(coreFailure('internal')).toBe('core_unavailable')
expect(coreFailure('invalid_json')).toBe('invalid_document')
})
it('a freed preview never rebuilds its handle', () => {
const preview = new CataloguePreview(
coreRuntime(),
{ status: 'published', document: JSON.stringify(document), fingerprint },
[{ assetId, sha256, bytes }],
)
const state = preview.state()
expect(state.ok && (state.value as PreviewState).status).toBe('published')
preview.free()
expect(preview.canvas('main')).toEqual({ ok: false, kind: 'core_unavailable' })
})
})
describe('catalogue cards (R4, board 30)', () => {
type Rpc = { rpc: (name: string, args?: unknown) => Promise<unknown> }
afterEach(() => vi.restoreAllMocks())
async function card(name: string): Promise<HTMLElement> {
return (await screen.findByRole('heading', { level: 2, name })).closest('article')!
}
/** The element carrying the notice's tone classes around a line of text. */
function noticeOf(text: HTMLElement): HTMLElement {
return text.closest('div.rounded-lg')!
}
function versionCalls(id: string): number {
return fake.rpcCalls.filter(
([n, a]) => n === 'get_sheet_version' && (a as { version_id: string }).version_id === id,
).length
}
/** Every `get_sheet_version` fails as a dropped request would. */
function failNetwork() {
fake.rpcResults.get_sheet_version = () => ({ error: { message: 'network' } })
}
/** Holds every later `get_sheet_version` answer until the returned release is called. */
function holdVersions(): () => void {
let release!: () => void
const gate = new Promise<void>((resolve) => (release = resolve))
const target = fake.client as unknown as Rpc
const original = target.rpc
target.rpc = async (name, args) => {
if (name === 'get_sheet_version') await gate
return original(name, args)
}
return release
}
async function failedCheval(text: string): Promise<HTMLElement> {
const cheval = await card('Cheval')
await within(cheval).findByText(text)
return cheval
}
it.each([
[
'a drawing whose bytes do not hash to its row',
() => {
const altered = bytes.slice()
altered[200] ^= 1
fake.storage.download.mockImplementation(async () => ({ data: new Blob([altered]), error: null }))
},
],
[
'a stored fingerprint the core does not recompute',
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) }),
],
[
'a drawing Storage answers 400 for',
() =>
fake.storage.download.mockImplementation(async () => ({ data: null, error: { status: 400, name: 'StorageApiError' } })),
],
[
'a drawing Storage answers 404 for',
() =>
fake.storage.download.mockImplementation(async () => ({ data: null, error: { status: 404, name: 'StorageApiError' } })),
],
[
'an unreadable document',
() => serveVersions({ [V3]: versionAnswer(V3, 'published', { document: { schema_version: 2 } }) }),
],
])('says the integrity failure of %s, without retry or live region', async (_case, arrange) => {
arrange()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.card.integrity_failed'])
expect(noticeOf(within(cheval).getByText(fr['catalogue.card.integrity_failed'])).className).toMatch(
/color-danger/,
)
expect(within(cheval).queryByRole('alert')).toBeNull()
expect(within(cheval).queryByRole('status')).toBeNull()
expect(within(cheval).queryByRole('button', { name: fr['common.retry'] })).toBeNull()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toHaveAttribute('href', `/app/anatomy/${SHEET}`)
expect(within(cheval).getByText(fr['catalogue.status.published'])).toBeInTheDocument()
expect(cheval.querySelector('img')).toBeNull()
})
it('says a network failure, retries that card and moves the focus to « Consulter »', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
expect(noticeOf(within(cheval).getByText(fr['catalogue.failure.network'])).className).toMatch(
/severity-moderate/,
)
const retries = within(cheval).getAllByRole('button', { name: fr['common.retry'] })
expect(retries).toHaveLength(1)
serveVersions({ [V3]: versionAnswer(V3, 'published') })
await userEvent.click(retries[0])
expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(within(cheval).queryByText(fr['catalogue.failure.network'])).toBeNull()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toHaveFocus()
})
it('keeps « Réessayer » focused during an attempt that fails again, then says the line politely', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const polite = cheval.querySelector('[aria-live="polite"]')!
expect(polite).toHaveTextContent('')
const release = holdVersions()
const retry = within(cheval).getByRole('button', { name: fr['common.retry'] })
await userEvent.click(retry)
expect(retry).toHaveFocus()
expect(retry).toHaveAttribute('aria-disabled', 'true')
// The attempt is seen, not only told: greyed with a wait cursor (no new wording).
expect(retry.className).toMatch(/aria-disabled:opacity-60/)
expect(retry.className).toMatch(/aria-disabled:cursor-wait/)
expect(cheval).toHaveAttribute('aria-busy', 'true')
expect(polite).toHaveTextContent('')
await act(async () => release())
await waitFor(() => expect(polite).toHaveTextContent(fr['catalogue.failure.network']))
expect(retry).toBeInTheDocument()
expect(retry).toHaveFocus()
expect(retry).not.toHaveAttribute('aria-disabled', 'true')
expect(cheval).not.toHaveAttribute('aria-busy', 'true')
})
it('reloads only the card whose « Réessayer » was pressed, with no burst of announcements', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const dog = await card('Chien, rachis')
await within(dog).findByText(fr['catalogue.failure.network'])
expect(screen.queryAllByRole('alert')).toHaveLength(0)
expect(within(cheval).queryByRole('status')).toBeNull()
expect(within(dog).queryByRole('status')).toBeNull()
const before = versionCalls(DOG)
const chevalBefore = versionCalls(V3)
await userEvent.click(within(cheval).getByRole('button', { name: fr['common.retry'] }))
const polite = cheval.querySelector('[aria-live="polite"]')!
await waitFor(() => expect(polite).toHaveTextContent(fr['catalogue.failure.network']))
expect(versionCalls(V3)).toBe(chevalBefore + 1)
expect(versionCalls(DOG)).toBe(before)
})
it('ignores a second click while the attempt runs', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const release = holdVersions()
const before = versionCalls(V3)
const retry = within(cheval).getByRole('button', { name: fr['common.retry'] })
await userEvent.click(retry)
await userEvent.click(retry)
await act(async () => release())
const polite = cheval.querySelector('[aria-live="polite"]')!
await waitFor(() => expect(polite).toHaveTextContent(fr['catalogue.failure.network']))
expect(versionCalls(V3)).toBe(before + 1)
})
it('moves the focus to « Consulter » and says the line when a retry ends with no retry left', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const polite = cheval.querySelector('[aria-live="polite"]')!
serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) })
await userEvent.click(within(cheval).getByRole('button', { name: fr['common.retry'] }))
// The region mounted before the attempt is the one that speaks (never mounted with its text).
await waitFor(() => expect(polite).toHaveTextContent(fr['catalogue.card.integrity_failed']))
expect(polite.isConnected).toBe(true)
expect(within(cheval).queryByRole('button', { name: fr['common.retry'] })).toBeNull()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toHaveFocus()
})
it('ignores a second retry call in the same tick', async () => {
vi.spyOn(coreRuntime(), 'ready').mockResolvedValueOnce(false)
const restart = vi.spyOn(coreRuntime(), 'retry')
mount('/app/anatomy')
const cheval = await failedCheval(fr['sheet.core_unavailable'])
const before = versionCalls(V3)
const retry = within(cheval).getByRole('button', { name: fr['sheet.core_retry'] })
act(() => {
fireEvent.click(retry)
fireEvent.click(retry)
})
expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(restart).toHaveBeenCalledTimes(1)
expect(versionCalls(V3)).toBe(before + 1)
})
it('drops a retry still running when the card leaves: no update, URLs and previews balanced', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const created = vi.spyOn(URL, 'createObjectURL')
const revoked = vi.spyOn(URL, 'revokeObjectURL')
const built = vi.spyOn(CataloguePreview.prototype, 'state')
const freed = vi.spyOn(CataloguePreview.prototype, 'free')
const errors = vi.spyOn(console, 'error')
const release = holdVersions()
serveVersions({ [V3]: versionAnswer(V3, 'published') })
await userEvent.click(within(cheval).getByRole('button', { name: fr['common.retry'] }))
await userEvent.type(screen.getByRole('searchbox', { name: fr['catalogue.search'] }), 'dog')
expect(screen.queryByRole('heading', { level: 2, name: 'Cheval' })).toBeNull()
await act(async () => release())
await waitFor(() => expect(freed).toHaveBeenCalled())
await act(async () => new Promise((resolve) => setTimeout(resolve, 20)))
expect(built.mock.calls.length).toBeGreaterThan(0)
expect(freed).toHaveBeenCalledTimes(built.mock.calls.length)
expect(created).not.toHaveBeenCalled()
expect(revoked).not.toHaveBeenCalled()
expect(errors).not.toHaveBeenCalled()
})
it('says the core failed to load and restarts it on « Réessayer »', async () => {
vi.spyOn(coreRuntime(), 'ready').mockResolvedValueOnce(false)
const restart = vi.spyOn(coreRuntime(), 'retry')
mount('/app/anatomy')
const cheval = await failedCheval(fr['sheet.core_unavailable'])
await userEvent.click(within(cheval).getByRole('button', { name: fr['sheet.core_retry'] }))
expect(restart).toHaveBeenCalledTimes(1)
expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(within(cheval).queryByText(fr['sheet.core_unavailable'])).toBeNull()
})
it('says the engine stopped for good in the error tone, with no « Réessayer »', async () => {
const setStopped = controlStopped(coreRuntime(), true)
try {
vi.spyOn(coreRuntime(), 'ready').mockResolvedValue(false)
mount('/app/anatomy')
const cheval = await failedCheval(fr['core.stopped'])
expect(noticeOf(within(cheval).getByText(fr['core.stopped'])).className).toMatch(/color-danger/)
expect(within(cheval).queryByRole('button', { name: fr['sheet.core_retry'] })).toBeNull()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toBeInTheDocument()
} finally {
act(() => setStopped(false))
}
})
it('restarts the engine and reloads only the card whose « Réessayer » was pressed (R-7)', async () => {
serveVersions({ [V3]: versionAnswer(V3, 'published'), [DOG]: versionAnswer(DOG, 'published') })
vi.spyOn(coreRuntime(), 'ready').mockResolvedValueOnce(false).mockResolvedValueOnce(false)
const restart = vi.spyOn(coreRuntime(), 'retry')
mount('/app/anatomy')
const cheval = await failedCheval(fr['sheet.core_unavailable'])
const dog = await card('Chien, rachis')
await within(dog).findByText(fr['sheet.core_unavailable'])
const dogCalls = versionCalls(DOG)
await userEvent.click(within(cheval).getByRole('button', { name: fr['sheet.core_retry'] }))
expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(restart).toHaveBeenCalledTimes(1)
expect(versionCalls(DOG)).toBe(dogCalls)
expect(within(dog).getByText(fr['sheet.core_unavailable'])).toBeInTheDocument()
expect(within(dog).getByRole('button', { name: fr['sheet.core_retry'] })).toBeInTheDocument()
})
it('says an expired session with « Réessayer »', async () => {
fake.rpcResults.get_sheet_version = () => ({ error: { message: 'session_expired' } })
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.session_expired'])
expect(within(cheval).getByRole('button', { name: fr['common.retry'] })).toBeInTheDocument()
})
it('says a refused version read with « Réessayer »', async () => {
mount('/app/anatomy')
const dog = await card('Chien, rachis')
expect(await within(dog).findByText(fr['access_denied.title'])).toBeInTheDocument()
expect(within(dog).getByRole('button', { name: fr['common.retry'] })).toBeInTheDocument()
})
it('says a version over the size limits apart from integrity, without retry (D1)', async () => {
vi.spyOn(CataloguePreview.prototype, 'state').mockReturnValueOnce({ ok: false, kind: 'caps' })
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.caps'])
expect(noticeOf(within(cheval).getByText(fr['catalogue.failure.caps'])).className).toMatch(/color-danger/)
expect(within(cheval).queryByText(fr['catalogue.card.integrity_failed'])).toBeNull()
expect(within(cheval).queryByRole('button', { name: fr['common.retry'] })).toBeNull()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toBeInTheDocument()
})
it('says the integrity failure in English', async () => {
useLocaleStore.setState({ locale: 'en' })
serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) })
mount('/app/anatomy')
const horse = await card('Horse')
expect(await within(horse).findByText(en['catalogue.card.integrity_failed'])).toBeInTheDocument()
})
/** The path data the Icon component draws for a name (no hook of its own). */
function iconPath(name: IconName): string | null {
const { container } = render(<Icon name={name} />)
const d = container.querySelector('path')!.getAttribute('d')
cleanup()
return d
}
it.each([
['a network line', 'network', 'catalogue.failure.network', 'wifi-off'],
['an unavailable line', 'boom', 'catalogue.failure.unavailable', 'alert'],
] as const)('draws the glyph of %s', async (_case, message, key, icon) => {
fake.rpcResults.get_sheet_version = () => ({ error: { message } })
const expected = iconPath(icon)
const other = iconPath(icon === 'alert' ? 'wifi-off' : 'alert')
mount('/app/anatomy')
const cheval = await failedCheval(fr[key])
const path = noticeOf(within(cheval).getByText(fr[key])).querySelector('svg path')!
expect(path.getAttribute('d')).toBe(expected)
expect(path.getAttribute('d')).not.toBe(other)
})
it('draws the alert glyph on an integrity line', async () => {
serveVersions({ [V3]: versionAnswer(V3, 'published', { fingerprint: 'a'.repeat(64) }) })
const expected = iconPath('alert')
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.card.integrity_failed'])
const path = noticeOf(within(cheval).getByText(fr['catalogue.card.integrity_failed'])).querySelector('svg path')!
expect(path.getAttribute('d')).toBe(expected)
})
it('moves the focus to « Consulter » when the attempt settles with the focus on the page body', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const release = holdVersions()
serveVersions({ [V3]: versionAnswer(V3, 'published') })
const retry = within(cheval).getByRole('button', { name: fr['common.retry'] })
await userEvent.click(retry)
act(() => retry.blur())
expect(globalThis.document.body).toHaveFocus()
await act(async () => release())
expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).toHaveFocus()
})
it('leaves the focus where it is when the attempt settles with the focus elsewhere', async () => {
failNetwork()
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.network'])
const release = holdVersions()
serveVersions({ [V3]: versionAnswer(V3, 'published') })
await userEvent.click(within(cheval).getByRole('button', { name: fr['common.retry'] }))
const search = screen.getByRole('searchbox', { name: fr['catalogue.search'] })
act(() => search.focus())
await act(async () => release())
expect(await within(cheval).findByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(search).toHaveFocus()
expect(within(cheval).getByRole('link', { name: 'Consulter Cheval' })).not.toHaveFocus()
})
it('classes every failure kind', () => {
const expected: Record<CatalogueFailure, [integrity: boolean, refused: boolean]> = {
fingerprint_mismatch: [true, true],
drawing_hash_mismatch: [true, true],
drawing_missing: [true, true],
invalid_document: [true, true],
caps: [false, true],
denied: [false, false],
network: [false, false],
session_expired: [false, false],
rate_limited: [false, false],
unavailable: [false, false],
core_unavailable: [false, false],
}
for (const [kind, [integrity, refused]] of Object.entries(expected)) {
const failure = kind as CatalogueFailure
expect(cardFailure(failure, false)).toEqual({ integrity, refused, retry: !refused })
const stoppedRetry = !refused && failure !== 'core_unavailable'
expect(cardFailure(failure, true)).toEqual({ integrity, refused, retry: stoppedRetry })
}
})
it('says a main view the core refuses to compose, with the counts (D2)', async () => {
vi.spyOn(CataloguePreview.prototype, 'canvas').mockReturnValueOnce({ ok: false, kind: 'view_refused' })
mount('/app/anatomy')
const cheval = await failedCheval(fr['catalogue.failure.view'])
const line = noticeOf(within(cheval).getByText(fr['catalogue.failure.view']))
expect(line.className).toMatch(/surface-strong/)
expect(within(cheval).queryByRole('status')).toBeNull()
expect(within(cheval).getByText(/2 vues, 27 zones de constats/)).toBeInTheDocument()
expect(within(cheval).queryByRole('button', { name: fr['common.retry'] })).toBeNull()
expect(cheval.querySelector('img')).toBeNull()
})
it('says the engine failed while composing the main view, with its retry (D2)', async () => {
vi.spyOn(CataloguePreview.prototype, 'canvas').mockReturnValueOnce({ ok: false, kind: 'core_unavailable' })
mount('/app/anatomy')
const cheval = await failedCheval(fr['sheet.core_unavailable'])
expect(within(cheval).getByRole('button', { name: fr['sheet.core_retry'] })).toBeInTheDocument()
})
})