Files
faunosteo/apps/app/tests/unit/components.AvatarSection.test.tsx
T
bchanot 926dd7df8c feat(app): profile photo — avatar upload in Mon compte, photo in the sidebar, drawer and top bar
packages/supabase assets module: closed AssetFailure kinds, begin / quarantine
upload (upsert off) / confirm / remove, own-row state read with an explicit
column list, download under the SELECT policy. App: client transport (magic
byte sniff, never SVG, createImageBitmap, canvas 1024 px, JPEG 0.9, 5 MiB
cap), AvatarSection (preview, save, 1 s polling up to 30 s, rejection and
failure messages per closed code, removal with confirmation, in-flight row
resumed at mount), auth store blob URL revoked on change and sign-out,
AvatarCircle in UserBadge and the top bar link to Mon compte (D3), FR/EN
strings, fake client extended, 27 new tests (app 300).
2026-10-13 19:32:37 +02:00

173 lines
8.0 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('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()
})
})