gongxiangp2/components/admin/MaterialPurgeStatus.test.tsx

34 lines
2.0 KiB
TypeScript

import React from 'react'
import { act, fireEvent, render, screen } from '@testing-library/react'
import { useMaterialPurgeJobs } from './MaterialPurgeStatus'
const id = '11111111-1111-4111-8111-111111111111'
const job = { id, materialId: id, name: '测试素材', status: 'queued', totalFiles: 2, processedFiles: 0, sharedFiles: 0, error: null }
const response = (body: unknown, ok = true) => Promise.resolve({ ok, json: async () => body })
function Fixture() { const { status } = useMaterialPurgeJobs(); return <>{status}</> }
beforeEach(() => { jest.useFakeTimers(); global.fetch = jest.fn() })
afterEach(() => { jest.useRealTimers(); jest.restoreAllMocks() })
test('刷新后重新接管的清理任务也显示完成结果', async () => {
;(fetch as jest.Mock).mockImplementationOnce(() => response({ jobs: [job] }))
.mockImplementation(() => response({ jobs: [{ ...job, status: 'completed', processedFiles: 2 }] }))
await act(async () => { render(<Fixture />) })
expect(screen.getByText('正在清理 1 条素材')).toBeInTheDocument()
await act(async () => { jest.advanceTimersByTime(3000) })
expect((fetch as jest.Mock).mock.calls[1][0]).toContain(`id=${id}`)
expect(screen.getByText('已彻底删除 1 条')).toBeInTheDocument()
})
test('后台进度轮询成功不能抹掉人工重试失败的提示', async () => {
const failed = { ...job, status: 'failed', error: '文件清理未完成' }
;(fetch as jest.Mock).mockImplementation((_url, options) => options?.method === 'POST'
? response({ error: '存储暂不可用,请稍后重试' }, false) : response({ jobs: [failed] }))
await act(async () => { render(<Fixture />) })
await act(async () => { fireEvent.click(screen.getByRole('button', { name: '重试清理' })) })
expect(screen.getByRole('alert')).toHaveTextContent('存储暂不可用,请稍后重试')
await act(async () => { jest.advanceTimersByTime(3000) })
expect(screen.getByRole('alert')).toHaveTextContent('存储暂不可用,请稍后重试')
expect(screen.getByRole('button', { name: '重试清理' })).toBeEnabled()
})