Files
faunosteo/apps/app/tests/unit/routes.clients.test.tsx
bchanot 567ad40c80 fix(app): the « Client introuvable » screen focuses its heading too
Every client screen focuses its heading when it opens (contract §11.7); the
not-found screen did not. Unit and Chromium tests now assert the focus.
Found by the V1-1.5 verifier.
2026-10-26 02:11:15 +01:00

372 lines
19 KiB
TypeScript

import { afterEach, 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, useLocation } from 'react-router-dom'
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
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 AppLayout from '@/components/shell/AppLayout'
import RequireWorkspace from '@/app/guards/RequireWorkspace'
import ClientsListRoute from '@/app/routes/app/clients/ClientsListRoute'
import ClientCreateRoute from '@/app/routes/app/clients/ClientCreateRoute'
import ClientDetailRoute from '@/app/routes/app/clients/ClientDetailRoute'
import ClientEditRoute from '@/app/routes/app/clients/ClientEditRoute'
import { SEARCH_DELAY_MS } from '@/clients/useClientList'
import { useAuthStore, type WorkspaceState } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
/**
* The client screens on a fake client: states, the calls they make and what
* they keep. The RPC signatures are checked by the compiler in
* packages/supabase and against real PostgREST in its sandbox suite; the
* journeys run in Chromium in e2e/shell/clients.spec.ts.
*/
const WS = '11111111-1111-4111-8111-111111111111'
const ID = '22222222-2222-4222-8222-222222222222'
let fake: FakeSupabase
function listRow(i: number, patch: Record<string, unknown> = {}) {
return {
id: `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`,
kind: 'person',
display_name: `Client ${String(i).padStart(2, '0')}`,
city: null,
phone: null,
email: null,
archived_at: null,
name_key: `client ${String(i).padStart(2, '0')}`,
current_animal_count: 0,
...patch,
}
}
function clientRow(patch: Record<string, unknown> = {}) {
return {
id: ID,
kind: 'person',
display_name: 'Marie Dupont',
email: null,
phone: null,
address_line1: null,
address_line2: null,
postal_code: null,
city: 'Lyon',
country: null,
revision: 1,
archived_at: null,
created_at: '2026-10-26T10:00:00Z',
updated_at: '2026-10-26T10:00:00Z',
...patch,
}
}
/** The page itself, without the shell's top bar (which repeats the page title). */
const page = () => within(screen.getByRole('main'))
const rpcArgs = (name: string) => fake.rpcCalls.filter(([n]) => n === name).map(([, a]) => a as Record<string, unknown>)
function Where() {
return <span data-testid="where">{useLocation().pathname}</span>
}
function mount(path: string, workspace: WorkspaceState = { status: 'ready', id: WS }) {
useAuthStore.setState({ status: 'signed_in', user: fakeUser(), profile: fakeProfile(), workspace })
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/app" element={<AppLayout />}>
<Route index element={<p>dashboard</p>} />
<Route path="clients" element={<RequireWorkspace />}>
<Route index element={<ClientsListRoute />} />
<Route path="new" element={<ClientCreateRoute />} />
<Route path=":clientId" element={<ClientDetailRoute />} />
<Route path=":clientId/edit" element={<ClientEditRoute />} />
</Route>
</Route>
</Routes>
<Where />
</MemoryRouter>,
)
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
fake.tables.clients = []
fake.rpcResults.search_clients = { data: [] }
fake.rpcResults.list_client_animals = { data: [] }
mocks.fake = fake
})
afterEach(() => {
cleanup()
vi.useRealTimers()
})
describe('RequireWorkspace', () => {
it.each([
[{ status: 'loading' }, 'workspace.loading'],
[{ status: 'inactive' }, 'workspace.inactive'],
[{ status: 'unconfirmed' }, 'workspace.unconfirmed'],
[{ status: 'missing' }, 'workspace.missing'],
] as const)('says %o and renders no client screen', (workspace, key) => {
mount('/app/clients', workspace)
expect(screen.getByText(fr[key])).toBeInTheDocument()
expect(page().queryByRole('heading', { level: 1, name: fr['clients.list.title'] })).toBeNull()
expect(fake.rpcCalls).toEqual([])
})
it('names a read failure and reads again on retry', async () => {
fake.tables.workspaces = [{ id: WS, personal_user_id: 'user-1' }]
mount('/app/clients', { status: 'error', failure: 'network' })
expect(screen.getByText(`${fr['workspace.error']} ${fr['clients.failure.network']}`)).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: fr['common.retry'] }))
expect(await page().findByRole('heading', { level: 1, name: fr['clients.list.title'] })).toBeInTheDocument()
})
it('remounts the screens on another workspace: no row of the previous one stays', async () => {
fake.rpcResults.search_clients = { data: [listRow(1, { display_name: 'Client de A' })] }
mount('/app/clients')
expect(await screen.findByText('Client de A')).toBeInTheDocument()
fake.rpcResults.search_clients = { data: [] }
act(() => useAuthStore.setState({ workspace: { status: 'loading' } }))
expect(screen.queryByText('Client de A')).toBeNull()
act(() => useAuthStore.setState({ workspace: { status: 'ready', id: '33333333-3333-4333-8333-333333333333' } }))
expect(await screen.findByText(fr['clients.list.empty'])).toBeInTheDocument()
expect(screen.queryByText('Client de A')).toBeNull()
expect(rpcArgs('search_clients').at(-1)?.workspace_id).toBe('33333333-3333-4333-8333-333333333333')
})
})
describe('client list', () => {
it('lists the first page in the workspace, focuses its heading, offers « Afficher plus »', async () => {
fake.rpcResults.search_clients = { data: Array.from({ length: 26 }, (_, i) => listRow(i + 1)) }
mount('/app/clients')
expect(await screen.findByText('Client 01')).toBeInTheDocument()
expect(page().getByRole('heading', { level: 1, name: fr['clients.list.title'] })).toHaveFocus()
expect(screen.getAllByRole('listitem')).toHaveLength(25)
expect(rpcArgs('search_clients')[0]).toMatchObject({ workspace_id: WS, query: '', archived: false, page_size: 26 })
fake.rpcResults.search_clients = { data: [listRow(26), listRow(27)] }
await userEvent.click(screen.getByRole('button', { name: fr['clients.list.more'] }))
expect(await screen.findByText('Client 27')).toBeInTheDocument()
expect(screen.getAllByRole('listitem')).toHaveLength(27)
expect(rpcArgs('search_clients').at(-1)).toMatchObject({ after_name_key: 'client 25', after_id: listRow(25).id })
expect(screen.queryByRole('button', { name: fr['clients.list.more'] })).toBeNull()
})
it('waits for a pause in typing before searching, once', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
mount('/app/clients')
await screen.findByText(fr['clients.list.empty'])
const before = rpcArgs('search_clients').length
const box = screen.getByRole('searchbox', { name: new RegExp(fr['clients.list.search_label']) })
for (const value of ['m', 'ma', 'mar', 'mari']) fireEvent.change(box, { target: { value } })
await act(() => vi.advanceTimersByTimeAsync(SEARCH_DELAY_MS + 10))
await waitFor(() => expect(rpcArgs('search_clients').length).toBe(before + 1))
expect(rpcArgs('search_clients').at(-1)?.query).toBe('mari')
expect(await screen.findByText(fr['clients.list.no_results'])).toBeInTheDocument()
})
it('switches to the archived clients', async () => {
mount('/app/clients')
await screen.findByText(fr['clients.list.empty'])
fake.rpcResults.search_clients = { data: [listRow(1, { archived_at: '2026-10-26T10:00:00Z' })] }
await userEvent.click(screen.getByRole('switch', { name: fr['clients.list.archived_toggle'] }))
expect(await screen.findByText(fr['clients.archived_badge'])).toBeInTheDocument()
expect(rpcArgs('search_clients').at(-1)?.archived).toBe(true)
})
it('names a failure and retries', async () => {
fake.rpcResults.search_clients = { error: { code: '', message: 'FetchError' } }
mount('/app/clients')
expect(await screen.findByText(fr['clients.failure.unavailable'])).toBeInTheDocument()
fake.rpcResults.search_clients = { data: [listRow(1)] }
await userEvent.click(screen.getByRole('button', { name: fr['common.retry'] }))
expect(await screen.findByText('Client 01')).toBeInTheDocument()
})
})
describe('client creation', () => {
it('refuses an empty name and focuses it, without a request', async () => {
mount('/app/clients/new')
await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
const name = screen.getByLabelText(new RegExp(fr['clients.form.display_name.person']))
expect(name).toHaveFocus()
expect(name).toHaveAttribute('aria-invalid', 'true')
expect(screen.getByText(fr['clients.error.required'])).toBeInTheDocument()
expect(rpcArgs('create_client')).toEqual([])
})
it('sends the same request id again after a lost answer, then opens the client', async () => {
fake.rpcResults.create_client = { error: { code: '', message: 'TypeError: fetch failed' } }
mount('/app/clients/new')
await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'Marie Dupont')
await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.phone'])), '06 12 34 56 78')
await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
expect(await screen.findByText(fr['clients.failure.unavailable'])).toBeInTheDocument()
fake.rpcResults.create_client = { data: { id: ID, revision: 1 } }
fake.tables.clients = [clientRow()]
await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(`/app/clients/${ID}`))
const [first, second] = rpcArgs('create_client')
expect(first.create_request_id).toBe(second.create_request_id)
expect(first).toMatchObject({ workspace_id: WS, kind: 'person', display_name: 'Marie Dupont', phone: '+33612345678' })
expect(await screen.findByText(fr['clients.detail.created'])).toBeInTheDocument()
})
it('a double click sends one creation', async () => {
let release: () => void = () => undefined
const pending = new Promise<void>((resolve) => (release = resolve))
const client = fake.client as unknown as { rpc: (n: string, a: unknown) => Promise<unknown> }
client.rpc = async (name, args) => {
fake.rpcCalls.push([name, args])
await pending
return { data: { id: ID, revision: 1 }, error: null }
}
mount('/app/clients/new')
await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'Double')
const submit = screen.getByRole('button', { name: fr['clients.form.submit_create'] })
fireEvent.click(submit)
fireEvent.click(submit)
fireEvent.submit(submit.closest('form') as HTMLFormElement)
await act(async () => release())
expect(rpcArgs('create_client')).toHaveLength(1)
})
it('a new form is a new intent: another request id', async () => {
fake.rpcResults.create_client = { error: { code: 'P0001', message: 'rate_limited' } }
const first = mount('/app/clients/new')
await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'A')
await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
expect(await screen.findByText(fr['clients.failure.rate_limited'])).toBeInTheDocument()
first.unmount()
mount('/app/clients/new')
await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'A')
await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
await screen.findByText(fr['clients.failure.rate_limited'])
const ids = rpcArgs('create_client').map((a) => a.create_request_id)
expect(ids[0]).not.toBe(ids[1])
})
it('says a divergent replay plainly', async () => {
fake.rpcResults.create_client = { error: { code: 'P0001', message: 'request_conflict' } }
mount('/app/clients/new')
await userEvent.type(screen.getByLabelText(new RegExp(fr['clients.form.display_name.person'])), 'B')
await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_create'] }))
expect(await screen.findByText(fr['clients.failure.request_conflict'])).toBeInTheDocument()
})
})
describe('client edit', () => {
it('on conflict shows the stored value beside the typed one, then saves at the new revision', async () => {
fake.tables.clients = [clientRow()]
mount(`/app/clients/${ID}/edit`)
const city = await screen.findByLabelText(new RegExp(fr['clients.form.city']))
await userEvent.clear(city)
await userEvent.type(city, 'Annecy')
fake.tables.clients = [clientRow({ city: 'Vevey', revision: 2 })]
fake.rpcResults.update_client = { error: { code: 'P0001', message: 'conflict' } }
await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_update'] }))
expect(await screen.findByText(fr['clients.form.conflict_title'])).toBeInTheDocument()
expect(city).toHaveValue('Annecy')
expect(screen.getByText(fr['clients.form.stored_value'].replace('{value}', 'Vevey'))).toBeInTheDocument()
fake.rpcResults.update_client = { data: { revision: 3 } }
await userEvent.click(screen.getByRole('button', { name: fr['clients.form.submit_update'] }))
await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(`/app/clients/${ID}`))
expect(rpcArgs('update_client').map((a) => a.expected_revision)).toEqual([1, 2])
expect(rpcArgs('update_client')[1]).toMatchObject({ city: 'Annecy', email: null })
})
it('an archived client has no form', async () => {
fake.tables.clients = [clientRow({ archived_at: '2026-10-26T11:00:00Z' })]
mount(`/app/clients/${ID}/edit`)
expect(await screen.findByText(fr['clients.detail.archived_notice'])).toBeInTheDocument()
expect(screen.queryByRole('button', { name: fr['clients.form.submit_update'] })).toBeNull()
})
})
describe('client page', () => {
it('shows the same « introuvable » for an unknown id and a malformed one', async () => {
mount(`/app/clients/${ID}`)
expect(await screen.findByRole('heading', { name: fr['clients.not_found.title'] })).toHaveFocus()
cleanup()
mount('/app/clients/not-an-id')
expect(await screen.findByRole('heading', { name: fr['clients.not_found.title'] })).toBeInTheDocument()
})
it('an archived client is read-only and can be restored', async () => {
fake.tables.clients = [clientRow({ archived_at: '2026-10-26T11:00:00Z', revision: 2 })]
mount(`/app/clients/${ID}`)
expect(await screen.findByText(fr['clients.detail.archived_notice'])).toBeInTheDocument()
expect(screen.queryByRole('link', { name: fr['clients.detail.edit'] })).toBeNull()
fake.rpcResults.set_client_archived = { data: { revision: 3 } }
fake.tables.clients = [clientRow({ revision: 3 })]
await userEvent.click(screen.getByRole('button', { name: fr['clients.detail.restore'] }))
expect(await screen.findByText(fr['clients.detail.restored'])).toBeInTheDocument()
expect(rpcArgs('set_client_archived')).toEqual([{ client_id: ID, archived: false }])
expect(await screen.findByRole('link', { name: fr['clients.detail.edit'] })).toBeInTheDocument()
})
it('archives after the confirmation, which refuses to close while the request runs', async () => {
fake.tables.clients = [clientRow()]
fake.rpcResults.client_archive_preview = {
data: { count: 1, animals: [{ id: '44444444-4444-4444-8444-444444444444', name: 'Éclair' }] },
}
let release: () => void = () => undefined
const pending = new Promise<void>((resolve) => (release = resolve))
const client = fake.client as unknown as { rpc: (n: string, a: unknown) => Promise<unknown> }
const rpc = client.rpc.bind(client)
client.rpc = async (name, args) => {
if (name === 'set_client_archived') {
fake.rpcCalls.push([name, args])
await pending
return { data: { revision: 2 }, error: null }
}
return rpc(name, args)
}
mount(`/app/clients/${ID}`)
await userEvent.click(await screen.findByRole('button', { name: fr['clients.detail.archive'] }))
const dialog = await screen.findByRole('dialog', { name: fr['clients.archive.title'] })
expect(await screen.findByText('Éclair')).toBeInTheDocument()
expect(screen.getByText(fr['clients.archive.sole_owner_one'])).toBeInTheDocument()
await userEvent.click(within(dialog).getByRole('button', { name: fr['clients.archive.confirm'] }))
await userEvent.click(within(dialog).getByRole('button', { name: fr['common.cancel'] }))
expect(dialog).toBeInTheDocument()
fake.tables.clients = [clientRow({ archived_at: '2026-10-26T11:00:00Z', revision: 2 })]
await act(async () => release())
expect(await screen.findByText(fr['clients.detail.archived'])).toBeInTheDocument()
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(rpcArgs('set_client_archived')).toEqual([{ client_id: ID, archived: true }])
})
})
describe('leave guard', () => {
it('asks before a link leaves a form with changes; staying keeps them', async () => {
mount('/app/clients/new')
const name = screen.getByLabelText(new RegExp(fr['clients.form.display_name.person']))
await userEvent.type(name, 'Brouillon')
await userEvent.click(screen.getByRole('link', { name: fr['common.cancel'] }))
expect(await screen.findByRole('dialog', { name: fr['leave.title'] })).toBeInTheDocument()
expect(screen.getByTestId('where')).toHaveTextContent('/app/clients/new')
await userEvent.click(screen.getByRole('button', { name: fr['leave.stay'] }))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(name).toHaveValue('Brouillon')
await userEvent.click(screen.getAllByRole('link', { name: fr['shell.nav.dashboard'] })[0])
await userEvent.click(await screen.findByRole('button', { name: fr['leave.confirm'] }))
await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(/^\/app$/))
})
it('lets a clean form go without asking', async () => {
mount('/app/clients/new')
await userEvent.click(screen.getByRole('link', { name: fr['common.cancel'] }))
await waitFor(() => expect(screen.getByTestId('where')).toHaveTextContent(/^\/app\/clients$/))
expect(screen.queryByRole('dialog')).toBeNull()
})
})