41 lines
2.2 KiB
TypeScript
41 lines
2.2 KiB
TypeScript
import { fireEvent, render, screen, waitFor } from '@testing-library/react'
|
|
import DocumentAssetViewer from './DocumentAssetViewer'
|
|
|
|
test('报告地址可用于 PDF 预览、打开和按原文件名下载,并能切换图片', async () => {
|
|
const pdfUrl = 'https://s3.jiansun.vip/gongxiangpan/public-display/certificate-report/material-1/pdf/report.pdf'
|
|
const imageUrl = 'https://s3.jiansun.vip/gongxiangpan/public-display/certificate-report/material-1/image/report.jpg'
|
|
const originalFetch = global.fetch
|
|
const originalCreate = URL.createObjectURL
|
|
const originalRevoke = URL.revokeObjectURL
|
|
const blob = new Blob(['%PDF-1.4'], { type: 'application/pdf' })
|
|
global.fetch = jest.fn().mockResolvedValue({ ok: true, blob: async () => blob })
|
|
URL.createObjectURL = jest.fn().mockReturnValue('blob:report')
|
|
URL.revokeObjectURL = jest.fn()
|
|
const open = jest.spyOn(window, 'open').mockImplementation(() => null)
|
|
let savedName = ''
|
|
const click = jest.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {
|
|
savedName = this.download
|
|
})
|
|
try {
|
|
render(<DocumentAssetViewer title="检测报告" items={[
|
|
{ id: 'pdf', fileName: '检测报告.pdf', fileUrl: pdfUrl, fileKind: 'pdf' },
|
|
{ id: 'image', fileName: '检测报告.jpg', fileUrl: imageUrl, fileKind: 'image' },
|
|
]} />)
|
|
expect(screen.getByTitle('检测报告.pdf')).toHaveAttribute('src', `${pdfUrl}#toolbar=0&navpanes=0&scrollbar=1`)
|
|
fireEvent.click(screen.getByRole('button', { name: '打开原文件' }))
|
|
expect(open).toHaveBeenCalledWith(pdfUrl, '_blank', 'noopener,noreferrer')
|
|
fireEvent.click(screen.getByRole('button', { name: '下载原文件' }))
|
|
await waitFor(() => expect(savedName).toBe('检测报告.pdf'))
|
|
expect(global.fetch).toHaveBeenCalledWith(pdfUrl)
|
|
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:report')
|
|
fireEvent.click(screen.getByRole('button', { name: '图片 · 检测报告.jpg' }))
|
|
expect(screen.getByAltText('检测报告.jpg')).toHaveAttribute('src', imageUrl)
|
|
} finally {
|
|
click.mockRestore()
|
|
open.mockRestore()
|
|
global.fetch = originalFetch
|
|
URL.createObjectURL = originalCreate
|
|
URL.revokeObjectURL = originalRevoke
|
|
}
|
|
})
|