我正在测试 React Dropzone我需要检查 onDrop 函数。该函数有两个参数(acceptedFiles 和 rejectedFiles)。我正在这样模拟文件:
let image = {
name: 'cat.jpg',
size: 1000,
type: 'image/jpeg'
};
然后在我的测试中,我这样做:
it('should call handleOnDrop with more than 5 acceptedFiles', () => {
const wrapper = mount(mockComponent());
for (let index = 0; index < 5; index++) {
images.push(image);
}
wrapper.find(Dropzone).simulate('drop', { dataTransfer: { files: images } });
expect(setUserNotificationsSpy).toHaveBeenCalledTimes(1);
});
这是我的 onDrop 函数:
const handleOnDrop = (acceptedFiles, rejectedFiles) => {
if (rejectedFiles && rejectedFiles.length) {
checkMaxFile(rejectedFiles, maxSize) && setUserNotifications('error_big_image');
}
acceptedFiles && acceptedFiles.length <= maxFiles ? onDrop(acceptedFiles) : setUserNotifications('more_than_5');
};
预期的结果是 handleOnDrop 返回 acceptedFiles 但返回 rejectedFiles,我不知道为什么。
Mime 类型没问题,还有大小。
这是来自 react-dropzone 的函数:
fileAccepted(file) {
// Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with
// that MIME type will always be accepted
return file.type === 'application/x-moz-file' || accepts(file, this.props.accept);
}
谢谢。
最佳答案
经过时
let image = {
name: 'cat.jpg',
size: 1000,
type: 'image/jpeg'
};
进入
wrapper.find(Dropzone).simulate('drop', { dataTransfer: { files: images } });
它会认为图像未定义或为空。 我能够解决这个问题的方法是
//Create a non-null file
const fileContents = "file contents";
const file = new Blob([fileContents], { type: "text/plain" });
wrapper.find(Dropzone).simulate("drop", { dataTransfer: { files: [file] } });
这当然是您对纯文本文件的处理方式。对于不同类型的图像,您需要指定图像类型而不是“text/plain”
关于javascript - 如何正确测试 React Dropzone onDrop 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44538606/