Files
faunosteo/apps/app/tests/unit/components.AvatarSection.test.tsx
T
bchanot 8371aa0a2a fix(ui): keep the photo confirmation open until the removal settles
The dialog closed before the request, focus went back to the remove button, then the button vanished and focus fell on the page. The confirmation now closes with the photo gone, Escape and Cancel wait for it, and ModalDialog restores focus after the commit so its fallback sees the opener removed. The sr-only file input leaves the tab order: it was an invisible tab stop.
2026-10-25 22:46:18 +01:00

192 lines
9.3 KiB
TypeScript

import { afterEach, 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 { AssetFailure } from '@faunosteo/supabase'
import {
createFakeSupabase,
fakeAssetRow,
fakeProfile,
fakeUser,
type FakeSupabase,
} from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({
fake: null as unknown,
prepare: vi.fn(),
}))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
vi.mock('@/account/avatarTransport', () => ({
prepareAvatarUpload: (...args: unknown[]) => mocks.prepare(...args),
}))
import AvatarSection, { POLL_INTERVAL_MS } from '@/components/account/AvatarSection'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
let fake: FakeSupabase
const TICKET = {
asset_id: '11111111-1111-4111-8111-111111111111',
bucket_id: 'avatars',
quarantine_key: 'quarantine/user-1/11111111-1111-4111-8111-111111111111/upload',
}
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
mocks.fake = fake
mocks.prepare.mockReset()
useAuthStore.setState({
status: 'signed_in',
user: fakeUser(),
profile: fakeProfile(),
roles: [],
avatar: { clean: null, inFlight: null, lastRejected: null },
avatarUrl: null,
})
fake.rpcResults.begin_avatar_upload = { data: TICKET }
})
afterEach(() => {
cleanup()
vi.useRealTimers()
})
function pick(file = new File([new Uint8Array([0xff, 0xd8, 0xff])], 'p.jpg', { type: 'image/jpeg' })) {
const input = screen.getByLabelText(fr['account.avatar.change'])
fireEvent.change(input, { target: { files: [file] } })
}
describe('AvatarSection', () => {
it('shows the monogram and no remove button without a photo', () => {
render(<AvatarSection />)
expect(screen.getByText('AL')).toBeInTheDocument()
expect(screen.queryByRole('button', { name: fr['account.avatar.remove'] })).toBeNull()
})
it('refuses a bad pick with the phrased message and makes no request', async () => {
mocks.prepare.mockRejectedValue(new AssetFailure('unsupported_type'))
render(<AvatarSection />)
pick()
expect(await screen.findByText(fr['account.avatar.error.unsupported_type'])).toBeInTheDocument()
expect(fake.rpcCalls).toEqual([])
expect(fake.storage.upload).not.toHaveBeenCalled()
})
it('shows the preview with save / cancel before any request', async () => {
mocks.prepare.mockResolvedValue({ blob: new Blob(['x'], { type: 'image/jpeg' }), previewUrl: 'blob:preview' })
render(<AvatarSection />)
pick()
const img = await screen.findByRole('img', { name: fr['account.avatar.alt'] })
expect(img).toHaveAttribute('src', 'blob:preview')
expect(screen.getByRole('button', { name: fr['account.avatar.save'] })).toBeInTheDocument()
expect(fake.rpcCalls).toEqual([])
await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.cancel'] }))
expect(screen.queryByRole('img')).toBeNull()
})
it('saves in order begin → upload → confirm, polls, then shows the photo', async () => {
const blob = new Blob([new Uint8Array(1234)], { type: 'image/jpeg' })
mocks.prepare.mockResolvedValue({ blob, previewUrl: 'blob:preview' })
render(<AvatarSection />)
pick()
await screen.findByRole('button', { name: fr['account.avatar.save'] })
vi.useFakeTimers({ shouldAdvanceTime: true })
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: fr['account.avatar.save'] }))
})
await waitFor(() => expect(fake.rpcCalls.map((c) => c[0])).toEqual(['begin_avatar_upload', 'confirm_asset_upload']))
expect(fake.rpcCalls[0][1]).toEqual({ declared_mime: 'image/jpeg', declared_size: 1234 })
expect(fake.storage.upload).toHaveBeenCalledWith(TICKET.quarantine_key, blob, { upsert: false, contentType: 'image/jpeg' })
expect(fake.rpcCalls[1][1]).toEqual({ asset_id: TICKET.asset_id })
expect(screen.getByText(fr['account.avatar.processing'])).toBeInTheDocument()
expect(screen.getByRole('button', { name: fr['account.avatar.change'] })).toBeDisabled()
// The worker finishes: the next poll sees the clean row and downloads it.
fake.tables.assets.push(fakeAssetRow({ id: TICKET.asset_id, created_at: '2026-10-13T11:00:00Z' }))
await act(async () => {
await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS + 50)
})
await waitFor(() => expect(screen.getByText(fr['account.avatar.saved'])).toBeInTheDocument())
expect(fake.storage.download).toHaveBeenCalledWith('profiles/user-1/asset-1/avatar.webp')
expect(screen.getByRole('button', { name: fr['account.avatar.remove'] })).toBeInTheDocument()
})
it('phrases a rejection per code once the poll settles', async () => {
mocks.prepare.mockResolvedValue({ blob: new Blob(['x']), previewUrl: 'blob:p' })
render(<AvatarSection />)
pick()
await screen.findByRole('button', { name: fr['account.avatar.save'] })
vi.useFakeTimers({ shouldAdvanceTime: true })
await act(async () => {
fireEvent.click(screen.getByRole('button', { name: fr['account.avatar.save'] }))
})
await waitFor(() => expect(fake.rpcCalls.length).toBe(2))
fake.tables.assets.push(fakeAssetRow({ id: TICKET.asset_id, status: 'rejected', rejection_reason: 'dimensions', created_at: '2026-10-13T11:00:00Z' }))
await act(async () => {
await vi.advanceTimersByTimeAsync(POLL_INTERVAL_MS + 50)
})
await waitFor(() => expect(screen.getByText(fr['account.avatar.rejected.dimensions'])).toBeInTheDocument())
})
it('phrases an RPC refusal and keeps the circle usable', async () => {
mocks.prepare.mockResolvedValue({ blob: new Blob(['x']), previewUrl: 'blob:p' })
fake.rpcResults.begin_avatar_upload = { error: { code: 'P0001', message: 'rate_limited', status: 400 } }
render(<AvatarSection />)
pick()
await userEvent.click(await screen.findByRole('button', { name: fr['account.avatar.save'] }))
expect(await screen.findByText(fr['account.avatar.error.rate_limited'])).toBeInTheDocument()
expect(fake.storage.upload).not.toHaveBeenCalled()
expect(screen.getByRole('button', { name: fr['account.avatar.change'] })).toBeEnabled()
})
it('removes the photo after the dialog confirmation', async () => {
useAuthStore.setState({ avatarUrl: 'blob:current', avatar: { clean: fakeAssetRow(), inFlight: null, lastRejected: null } })
fake.rpcResults.remove_avatar = { data: 1 }
render(<AvatarSection />)
expect(screen.getByRole('img', { name: fr['account.avatar.alt'] })).toHaveAttribute('src', 'blob:current')
await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.remove'] }))
const dialog = await screen.findByRole('dialog', { name: fr['account.avatar.remove_title'] })
expect(dialog).toBeInTheDocument()
await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.remove_confirm'] }))
expect(await screen.findByText(fr['account.avatar.removed'])).toBeInTheDocument()
expect(fake.rpcCalls).toEqual([['remove_avatar', undefined]])
expect(useAuthStore.getState().avatarUrl).toBeNull()
expect(screen.queryByRole('img')).toBeNull()
})
it('keeps the confirmation open until the removal settles, then focuses the photo control', async () => {
useAuthStore.setState({ avatarUrl: 'blob:current', avatar: { clean: fakeAssetRow(), inFlight: null, lastRejected: null } })
let settle: (value: { data: number; error: null }) => void = () => {}
vi.spyOn(fake.client, 'rpc').mockImplementationOnce(
() => new Promise((resolve) => (settle = resolve)) as unknown as ReturnType<typeof fake.client.rpc>,
)
render(<AvatarSection />)
await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.remove'] }))
const dialog = await screen.findByRole('dialog', { name: fr['account.avatar.remove_title'] })
await userEvent.click(screen.getByRole('button', { name: fr['account.avatar.remove_confirm'] }))
fireEvent.keyDown(dialog, { key: 'Escape' })
await userEvent.click(screen.getByRole('button', { name: fr['common.cancel'] }))
expect(dialog).toBeInTheDocument()
await act(async () => settle({ data: 1, error: null }))
await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull())
expect(screen.queryByRole('button', { name: fr['account.avatar.remove'] })).toBeNull()
await waitFor(() => expect(screen.getByRole('button', { name: fr['account.avatar.change'] })).toHaveFocus())
})
it('resumes the processing state for a row in flight at mount', async () => {
useAuthStore.setState({ avatar: { clean: null, inFlight: fakeAssetRow({ status: 'uploaded' }), lastRejected: null } })
render(<AvatarSection />)
expect(screen.getByText(fr['account.avatar.processing'])).toBeInTheDocument()
expect(screen.getByRole('button', { name: fr['account.avatar.change'] })).toBeDisabled()
})
it('shows the last rejection of a fresh mount', () => {
useAuthStore.setState({ avatar: { clean: null, inFlight: null, lastRejected: fakeAssetRow({ status: 'rejected', rejection_reason: 'decode_failed' }) } })
render(<AvatarSection />)
expect(screen.getByText(fr['account.avatar.rejected.decode_failed'])).toBeInTheDocument()
})
})