我正在使用 Ant Design 的 Upload 组件。
<Upload
accept=".xlsx"
onChange={onImport}
>
<Button>Upload</Button>
</Upload>
我试图使用 fireEvent.change 模拟更改,它什么都不做:const inputEl = screen.getByText('Import');
const file = new File(['(⌐□_□)'], 'chucknorris.xlsx');
fireEvent.change(inputEl, { target: { files: [file] } });
我也尝试使用fireEvent.drop。我尝试设置 dataTransfer 和 files 属性。Object.defineProperty(inputEl, 'dataTransfer', {
value: {
files: [file]
}
});
Object.defineProperty(inputEl, 'files', {
value: [file]
});
fireEvent.drop(inputEl);
这会触发上传,但我不断收到以下错误:Cannot read property 'files' of undefined
at AjaxUploader._this.onFileDrop (node_modules/rc-upload/lib/AjaxUploader.js:108:63)
如何测试 Ant Design 的上传?
最佳答案
这是我如何处理它。自 input
是隐藏的,你不能用 RTL 查询它我只是用 document
查询了输入像这样:
async simulateFileUpload() {
const file = new File(['(⌐□_□)'], 'chucknorris.png', { type: 'image/png' });
const hiddenFileInput = document.querySelector('input[type="file"]') as Element;
await act(async () => {
fireEvent.change(hiddenFileInput, { target: { files: [file] } });
});
}
这不是最漂亮的事情,但它是测试上传功能的唯一方法。我包裹了
fireEvent
在 await act()
但这只是因为上传会触发我的应用程序中的某些状态更改,您当然可以直接将其扔掉
关于reactjs - 如何使用 React 测试库通过 Ant Design Upload 模拟上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64036136/