I’m testing React Dropzone and I need to check the onDrop function. This function has two parameters (acceptedFiles and rejectedFiles). I’m mocking the files like this:
JavaScript
x
6
1
let image = {
2
name: 'cat.jpg',
3
size: 1000,
4
type: 'image/jpeg'
5
};
6
Then in my test, I do that:
JavaScript
1
12
12
1
it('should call handleOnDrop with more than 5 acceptedFiles', () => {
2
const wrapper = mount(mockComponent());
3
4
for (let index = 0; index < 5; index++) {
5
images.push(image);
6
}
7
8
wrapper.find(Dropzone).simulate('drop', { dataTransfer: { files: images } });
9
10
expect(setUserNotificationsSpy).toHaveBeenCalledTimes(1);
11
});
12
This is my onDrop function:
JavaScript
1
8
1
const handleOnDrop = (acceptedFiles, rejectedFiles) => {
2
if (rejectedFiles && rejectedFiles.length) {
3
checkMaxFile(rejectedFiles, maxSize) && setUserNotifications('error_big_image');
4
}
5
6
acceptedFiles && acceptedFiles.length <= maxFiles ? onDrop(acceptedFiles) : setUserNotifications('more_than_5');
7
};
8
The expected result would be that handleOnDrop returns acceptedFiles but returns rejectedFiles and I don’t know why.
Mime type it’s ok and also size.
That’s the function from react-dropzone:
JavaScript
1
6
1
fileAccepted(file) {
2
// Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with
3
// that MIME type will always be accepted
4
return file.type === 'application/x-moz-file' || accepts(file, this.props.accept);
5
}
6
Thanks.
Advertisement
Answer
When passing
JavaScript
1
6
1
let image = {
2
name: 'cat.jpg',
3
size: 1000,
4
type: 'image/jpeg'
5
};
6
Into
JavaScript
1
2
1
wrapper.find(Dropzone).simulate('drop', { dataTransfer: { files: images } });
2
It will think image is undefined or null. The way I was able to fix this is
JavaScript
1
6
1
//Create a non-null file
2
const fileContents = "file contents";
3
const file = new Blob([fileContents], { type: "text/plain" });
4
5
wrapper.find(Dropzone).simulate("drop", { dataTransfer: { files: [file] } });
6
This of course is how you would do it for a plain text file. For different types of images you will want to specify the image type instead of doing “text/plain”