Skip to content

Commit

Permalink
test: verify the successfully uploaded file
Browse files Browse the repository at this point in the history
  • Loading branch information
Layouwen committed Nov 12, 2024
1 parent 3d157eb commit ff3fec0
Showing 1 changed file with 31 additions and 17 deletions.
48 changes: 31 additions & 17 deletions src/components/image-uploader/tests/image-uploader.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,12 +65,14 @@ describe('ImageUploader', () => {
})

const App = forwardRef<ImageUploaderRef, any>((props, ref) => {
const { onChange: propsOnChange, ...restProps } = props
const [fileList, setFileList] = useState<ImageUploadItem[]>([
{
url: demoSrc,
},
])
const { onChange: propsOnChange, defaultFileList, ...restProps } = props
const [fileList, setFileList] = useState<ImageUploadItem[]>(
defaultFileList || [
{
url: demoSrc,
},
]
)
const onChange = (newFileList: ImageUploadItem[]) => {
setFileList(newFileList)
propsOnChange?.(newFileList)
Expand Down Expand Up @@ -398,32 +400,44 @@ describe('ImageUploader', () => {
test('get all upload url', async () => {
function mockUploadWithFailure(failOnCount: number) {
let count = 0
return async () => {
return async (file: File) => {
count++
if (count === failOnCount) {
if (count === failOnCount + 1) {
throw new Error('Fail to upload')
}
return {
url: 'count: ' + count,
url: URL.createObjectURL(file),
extra: {
fileName: file.name,
},
}
}
}

const fn = jest.fn()
const mockUpload = mockUploadWithFailure(2)
const FAIL_INDEX = 1
const mockUpload = mockUploadWithFailure(FAIL_INDEX)

render(<App multiple upload={mockUpload} onChange={fn} />)
render(
<App multiple defaultFileList={[]} upload={mockUpload} onChange={fn} />
)

mockInputFile([
new File(['one'], 'one.png', { type: 'image/png' }),
new File(['two'], 'two.png', { type: 'image/png' }),
new File(['three'], 'three.png', { type: 'image/png' }),
])
const fileNameList = ['one.png', 'two.png', 'three.png']

mockInputFile(
fileNameList.map(name => new File([name], name, { type: 'image/png' }))
)

await act(async () => {
jest.runAllTimers()
})

expect(fn.mock.lastCall[0].length).toBe(3)
expect(fn.mock.lastCall[0].length).toBe(2)

const successFileNames = fileNameList.filter((_, i) => i !== FAIL_INDEX)
const mockInputSuccessFileNames = fn.mock.lastCall[0].map(
(item: ImageUploadItem) => item.extra.fileName
)
expect(successFileNames).toEqual(mockInputSuccessFileNames)
})
})

0 comments on commit ff3fec0

Please sign in to comment.