How to check React Dropzone onDrop method correctly

I am testing React Dropzone and I need to test the onDrop function. This function has two parameters (acceptFiles and rejectedFiles). I mock files like this:

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

Then in my test I do this:

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 acceptFiles but returns rejectedFiles, and I don't know why.

MIME is normal as well as size.

This is a function from the 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);
  }

Thank.

+9
source share
2 answers

Upon transfer

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

AT

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

It will read the image as 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] } });

, , , . "text/plain"

+7

, useDropzone.

wrapper.find(...).simulate('drop', ...);

.

change input. . , . , react-dropzone , , , , input. - , Dropzone.

wrapper.find('input').simulate('change', {
  target: { files },
  preventDefault: () => {},
  persist: () => {},
});

files :

const createFile = (name, size, type) => ({
  name,
  path: name,
  size,
  type,
});

const files = [
  createFile('foo.png', 200, 'image/png'),
  createFile('bar.jpg', 200, 'image/jpeg'),
];

, , , , native File. (, lastModifiedDate), , .

- , File, :

const createFile = (name, size, type) => {
  // the first arg, [], is the file content
  // it irrelevant, so I left it blank
  // you can fill it like ['foobar'] or [name] if you want to
  const file = new File([], name, { type });
  Reflect.defineProperty(file, 'size', {
    get() {
      return size;
    }
  });
  return file;
};

- , path . File . {}, , , . , , IMO, File, . .

+1

Source: https://habr.com/ru/post/1679222/


All Articles