使用Testing-Library测试React文件选择时fileInput.files返回空对象问题
解决Testing-Library测试文件选择时fileInput.files为空的问题
核心问题与修复步骤
- 必须等待异步操作完成:
userEvent.upload是异步方法,需用await等待执行完毕,否则代码会在文件上传操作完成前就读取files,导致获取不到结果。 - 正确处理FileList的打印:
fileInput.files返回的是FileList类数组对象,直接console.log会显示为空对象{},但实际可通过索引(如fileInput.files[0])或Array.from转换后查看内容。
修正后的测试代码
import { waitFor } from '@testing-library/react' import userEvent from '@testing-library/user-event' import React from 'react' import { renderWithProviders } from 'testing/renderWithProviders' import { FileSelectionDialogContent } from './fileSelectionDialogContent' test('Show a file selection dialog and test file selection', async () => { const file = new File(['hello'], 'hello.png', { type: 'image/png' }) const rendered = renderWithProviders(<FileSelectionDialogContent onFileSelect={() => {}} />) const fileInput = rendered.container.querySelector('input[type="file"]') as HTMLInputElement expect(fileInput).not.toBeNull() // 等待upload异步操作完成 await userEvent.upload(fileInput, file) // 正确获取并打印文件 console.log('Selected file =====> ', fileInput.files[0]) // 或者转换为数组查看 console.log('Files array =====> ', Array.from(fileInput.files)) // 断言验证文件是否正确上传 expect(fileInput.files[0]).toEqual(file) })
额外说明
如果组件在文件选择后有状态更新或UI变化,可使用waitFor包裹断言,确保组件完成渲染更新后再验证结果:
await waitFor(() => { expect(fileInput.files[0]).toEqual(file) })
内容的提问来源于stack exchange,提问作者podeig
相关产品推荐
相关产品推荐

