javascript - 如何正确测试 React Dropzone onDrop 方法

标签 javascript reactjs unit-testing jestjs react-dropzone

我正在测试 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/

相关文章:

javascript - 通知子组件 Promise 已结束,以便子组件可以执行方法(React Native)

javascript - 将 Canvas DataURL 转换为图像以发布到 Facebook

javascript - React - 在渲染期间更新状态会产生错误

javascript - 重复捕获组

javascript - jquery 验证和引导 btn。错误放置

javascript - React如何动态设置div的offsetTop和高度

javascript - 如何使用 React.js 在 5 秒后隐藏消息

java - 如何在java中使用假数据创建对象?

python - 魔术模拟 assert_called_once 与 assert_called_once_with 奇怪的行为

java - Spring:在 JUnit 测试中测试 JSP 输出