import { fireEvent, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { PerformanceSurveyAttachments } from '@/components/performance-survey-attachments'
import type { PerformanceCaseAttachment } from '@/lib/performance-survey-attachment-contract'
const base: PerformanceCaseAttachment = {
id: 'test-attachment', originalName: '项目说明.docx', kind: 'document', size: 1024,
status: 'ready', pageCount: 101, previewPageCount: 100, error: null,
}
test('keyboard opens and closes previews and selects pages within the cap', async () => {
const user = userEvent.setup()
render()
const toggle = screen.getByRole('button', { name: '展开预览' })
toggle.focus()
await user.keyboard('{Enter}')
expect(toggle).toHaveAttribute('aria-expanded', 'true')
expect(screen.getByText('共101页,预览前100页。下载原件可查看完整内容。')).toBeInTheDocument()
await user.click(screen.getByRole('button', { name: '下一页' }))
expect(screen.getByAltText('项目说明.docx 第2页')).toHaveAttribute('src', expect.stringContaining('page=2'))
fireEvent.change(screen.getByRole('combobox', { name: '页码' }), { target: { value: '100' } })
expect(screen.getByRole('button', { name: '下一页' })).toBeDisabled()
toggle.focus()
await user.keyboard(' ')
expect(toggle).toHaveAttribute('aria-expanded', 'false')
expect(toggle).toHaveFocus()
})
test('a failed document page has an actionable reload', async () => {
const user = userEvent.setup()
render()
await user.click(screen.getByRole('button', { name: '展开预览' }))
fireEvent.error(screen.getByRole('img'))
expect(screen.getByRole('alert')).toHaveTextContent('预览页读取失败')
await user.click(screen.getByRole('button', { name: '重新读取' }))
expect(screen.getByRole('img')).toBeInTheDocument()
})
test('failed conversion retains original download and retries the existing attachment', async () => {
const user = userEvent.setup()
const request = jest.fn().mockResolvedValue({ ...base, status: 'queued' })
render()
expect(screen.getByRole('link', { name: '下载原件' })).toHaveAttribute('href', '/api/performance-survey/case-attachments/test-attachment/file')
await user.click(screen.getByRole('button', { name: '展开预览' }))
await user.click(screen.getByRole('button', { name: '重新生成预览' }))
expect(request).toHaveBeenCalledWith('/case-attachments/test-attachment/retry', { method: 'POST' })
await waitFor(() => expect(screen.getByRole('status')).toHaveTextContent('等待生成预览'))
})