Files
faunosteo/apps/app/tests/unit/char.clickChain.test.tsx
T
bchanot 8673475293 chore(workspace): move the app to apps/app under a pnpm workspace (step 2)
144 files moved with git mv (pure renames). Root package.json delegates
dev/typecheck/test:run/lint/build to the packages; Node 24 LTS and
pnpm 10.13.1 pinned (.nvmrc, .node-version, engines, packageManager,
root devDependency, engine-strict). Dockerfile builds @faunosteo/app on
node:24-alpine and copies apps/app/dist; nginx and runtime config
unchanged. CI workflow for Gitea Actions. packages/ reserved (README only).
Docs synced: WORKSPACE.md, CLAUDE.md, README, DEPLOY, CHANGELOG, plan.
271/271 tests, typecheck, lint, build green from the root.
2026-10-08 21:51:13 +02:00

294 lines
12 KiB
TypeScript

/**
* Characterisation (Step 1): the zone-click chain of EditorRoute
* (onZoneClick → detail / fallback / spine / bilateral / toggle), the
* disclaimer-once-per-session rule, the zone removal and the pickers'
* integration with the store. Exercised through the rendered route on the
* real Horse.svg / Horse_head.svg, with loadSvg mocked to read the files.
*
* Limitation: the chain lives inside the route component (audit 13 §4, no
* unit seam). These tests go through the DOM; plan Step 5 extracts the
* chain into a service and will replace them with unit tests one-to-one.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, waitFor, within, cleanup } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import EditorRoute from '@/app/routes/EditorRoute'
import { useReportStore } from '@/state/reportStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import minimal from '../fixtures/report-v2.minimal.json'
import type { Report } from '@/domain/schema/report'
const HERE = dirname(fileURLToPath(import.meta.url))
const FILES: Record<string, string> = {
'/species/equine/Horse.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse.svg'), 'utf8'),
'/species/equine/Horse_head.svg': readFileSync(resolve(HERE, '../../public/species/equine/Horse_head.svg'), 'utf8'),
}
vi.mock('@/anatomy/svgLoader', () => ({
loadSvg: vi.fn(async (path: string) => {
const text = FILES[path]
if (!text) throw new Error(`unexpected path ${path}`)
const doc = new DOMParser().parseFromString(text, 'image/svg+xml')
return doc.documentElement as unknown as SVGSVGElement
}),
}))
const HINGE = 'point-mpbwyyc9' // Charnière C7-T1, plain point
const HIP = 'point-mpbwtst0' // bilateral
const CERVICAL = 'zone-mpbx5hx2' // vertebral-precision
const TRIGGER = 'zone-mpby55kd' // opens-detail=head
const ATM = 'point-mpbyo7zq' // in Horse_head.svg
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
function seedReport(observations: Report['observations'] = []) {
useReportStore.setState({ report: null, activeObservationIndex: 0 })
useReportStore.getState().initReport({
...(minimal as Report),
observations,
} as Omit<Report, 'id' | 'createdAt' | 'version'>)
}
const zonesOf = (i = 0) => useReportStore.getState().report!.observations[i].zones
const activeIndex = () => useReportStore.getState().activeObservationIndex
async function mount() {
const utils = render(
<MemoryRouter initialEntries={['/editor']}>
<EditorRoute />
</MemoryRouter>,
)
// Main SVG rendered and parsed (bones map ready once the trigger exists).
await waitFor(() => expect(document.querySelector(`[data-anno-id="${TRIGGER}"]`)).not.toBeNull())
// Give the bones state effect a tick so onZoneClick resolves ids.
await waitFor(() => expect(screen.queryByRole('dialog', { name: fr['editor.disclaimer_title'] })).toBeNull())
return utils
}
function clickZone(id: string, scope: ParentNode = document) {
const els = scope.querySelectorAll(`[data-anno-id="${id}"]`)
expect(els.length, id).toBeGreaterThan(0)
els[0].dispatchEvent(new Event('click', { bubbles: true }))
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
sessionStorage.clear()
sessionStorage.setItem(DISCLAIMER_FLAG, '1')
window.scrollTo = vi.fn() as unknown as typeof window.scrollTo
seedReport()
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
})
describe('disclaimer', () => {
it('shows the catalog scope_disclaimer once per session and records the flag', async () => {
sessionStorage.removeItem(DISCLAIMER_FLAG)
render(
<MemoryRouter initialEntries={['/editor']}>
<EditorRoute />
</MemoryRouter>,
)
const dialog = await screen.findByRole('dialog', { name: fr['editor.disclaimer_title'] })
expect(dialog.textContent).toContain('Aucun diagnostic médical')
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.understood'] }))
expect(sessionStorage.getItem(DISCLAIMER_FLAG)).toBe('1')
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
})
})
describe('plain zone (toggle)', () => {
it('adds the zone on first click and removes it on second click', async () => {
await mount()
clickZone(HINGE)
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HINGE }]))
clickZone(HINGE)
await waitFor(() => expect(zonesOf()).toEqual([]))
})
it('highlights the zone of the active observation with data-state="current"', async () => {
await mount()
clickZone(HINGE)
await waitFor(() =>
expect(document.querySelector(`[data-anno-id="${HINGE}"]`)?.getAttribute('data-state')).toBe('current'),
)
})
})
describe('no active observation (fallback)', () => {
it('re-activates the last observation and drops the click (user must click again)', async () => {
await mount()
// Collapse the only card through the UI (sets activeObservationIndex to -1).
await userEvent.click(screen.getByRole('button', { name: `${fr['observation.collapse_aria']} 1` }))
await waitFor(() => expect(activeIndex()).toBe(-1))
clickZone(HINGE)
await waitFor(() => expect(activeIndex()).toBe(0))
expect(zonesOf()).toEqual([])
clickZone(HINGE)
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HINGE }]))
})
})
describe('detail trigger', () => {
it('opens the detail modal, never adds the trigger as a zone, and zones clicked inside carry detailSourceId', async () => {
await mount()
clickZone(TRIGGER)
const dialog = await screen.findByRole('dialog', { name: `${fr['editor.detail_title_prefix']}head` })
expect(zonesOf()).toEqual([])
await waitFor(() => expect(dialog.querySelector(`[data-anno-id="${ATM}"]`)).not.toBeNull())
clickZone(ATM, dialog)
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: ATM, detailSourceId: 'head' }]))
// Toggle off from inside the modal uses the same (boneId, detailSourceId) identity.
clickZone(ATM, dialog)
await waitFor(() => expect(zonesOf()).toEqual([]))
})
})
describe('spine zone (vertebral-precision)', () => {
it('adds the zone, opens the picker on the matching region, and never toggles off on re-click', async () => {
await mount()
clickZone(CERVICAL)
const dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
expect(zonesOf()).toEqual([{ boneId: CERVICAL }])
expect(within(dialog).getByRole('tab', { name: fr['vertebra.region.C'] })).toHaveAttribute('aria-selected', 'true')
await userEvent.click(within(dialog).getByRole('button', { name: 'C3' }))
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] }))
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: CERVICAL, vertebrae: [{ region: 'C', index: 3 }] }]))
clickZone(CERVICAL)
await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
expect(zonesOf()).toHaveLength(1)
})
it('cancelling the picker leaves a spine zone without vertebrae', async () => {
await mount()
clickZone(CERVICAL)
const dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.cancel'] }))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(zonesOf()).toEqual([{ boneId: CERVICAL }])
})
it('picking another region in the picker spawns that region zone and pruning to zero removes a zone', async () => {
await mount()
clickZone(CERVICAL)
let dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
await userEvent.click(within(dialog).getByRole('button', { name: 'C3' }))
await userEvent.click(within(dialog).getByRole('tab', { name: fr['vertebra.region.L'] }))
await userEvent.click(within(dialog).getByRole('button', { name: 'L2' }))
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] }))
await waitFor(() =>
expect(zonesOf()).toEqual([
{ boneId: CERVICAL, vertebrae: [{ region: 'C', index: 3 }] },
{ boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L', index: 2 }] },
]),
)
clickZone(CERVICAL)
dialog = await screen.findByRole('dialog', { name: /Préciser les vertèbres/ })
await userEvent.click(within(dialog).getByRole('button', { name: 'C3' })) // uncheck
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.confirm'] }))
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: 'zone-mpbx1rm9', vertebrae: [{ region: 'L', index: 2 }] }]))
})
})
describe('bilateral zone', () => {
it('asks for a side, adds one zone per side, and clears both when both are present', async () => {
await mount()
clickZone(HIP)
let dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' })
await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.left'] }))
await waitFor(() => expect(zonesOf()).toEqual([{ boneId: HIP, side: 'left' }]))
clickZone(HIP)
dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' })
expect(within(dialog).getByRole('button', { name: fr['lateral.left'] })).toBeDisabled()
await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.right'] }))
await waitFor(() =>
expect(zonesOf()).toEqual([
{ boneId: HIP, side: 'left' },
{ boneId: HIP, side: 'right' },
]),
)
clickZone(HIP)
await waitFor(() => expect(zonesOf()).toEqual([]))
expect(screen.queryByRole('dialog')).toBeNull()
})
it('"both" adds the missing sides only', async () => {
await mount()
clickZone(HIP)
const dialog = await screen.findByRole('dialog', { name: 'Hanche (coxo-fémorale)' })
await userEvent.click(within(dialog).getByRole('button', { name: fr['lateral.both'] }))
await waitFor(() =>
expect(zonesOf()).toEqual([
{ boneId: HIP, side: 'left' },
{ boneId: HIP, side: 'right' },
]),
)
})
})
describe('zone removal and orphan findings', () => {
it('KNOWN: removing a zone via ✕ keeps the findings attached to its catalog zone', async () => {
seedReport([
{
id: 'obs-a',
zones: [{ boneId: HINGE }],
findings: [
{
zoneId: 'c7-t1',
path: ['c7-t1-dysfunctions', 'segmental', 'fixation'],
labelFrSnapshot: 'Fixation de la charnière',
labelEnSnapshot: 'Junction fixation',
},
],
freeTextFindings: [],
comment: '',
},
])
await mount()
const remove = await screen.findByRole('button', {
name: `${fr['observation.remove_zone']} Charnière C7-T1 (cervico-thoracique)`,
})
await userEvent.click(remove)
await waitFor(() => expect(zonesOf()).toEqual([]))
expect(useReportStore.getState().report!.observations[0].findings).toHaveLength(1)
})
it('shows one findings picker per (catalog zone, side) resolved by label match', async () => {
seedReport([
{
id: 'obs-b',
zones: [
{ boneId: HIP, side: 'left' },
{ boneId: HIP, side: 'right' },
{ boneId: HINGE },
{ boneId: TRIGGER },
],
findings: [],
freeTextFindings: [],
comment: '',
},
])
await mount()
await screen.findByRole('button', { name: /Hanche \(coxo-fémorale\) \(Gauche\)/ })
screen.getByRole('button', { name: /Hanche \(coxo-fémorale\) \(Droite\)/ })
screen.getByRole('button', { name: /^Charnière C7-T1 \(cervico-thoracique\)$/ })
// The trigger has no label and no catalog zone: exactly 3 pickers, and its
// badge falls back to the raw boneId.
expect(document.querySelectorAll('[aria-controls^="findings-zone-"]')).toHaveLength(3)
expect(
screen.getByRole('button', { name: `${fr['observation.remove_zone']} ${TRIGGER}` }),
).toBeInTheDocument()
})
})