Skip to content
Advertisement

How to test properly React Dropzone onDrop method

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:

let image = {
  name: 'cat.jpg',
  size: 1000,
  type: 'image/jpeg'
};

Then in my test, I do that:

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);
});

This is my onDrop function:

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');
};

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:

  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);
  }

Thanks.

Advertisement

Answer

When passing

let image = {
  name: 'cat.jpg',
  size: 1000,
  type: 'image/jpeg'
};

Into

wrapper.find(Dropzone).simulate('drop', { dataTransfer: { files: images } });

It will think image is undefined or null. The way I was able to fix this is

//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] } });

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”

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement