我怎样才能开玩笑地模拟 FileReader?

How can I mock FileReader with jest?

在过去的几周里,我一直在努力使用 jest 对文件上传 React 组件进行单元测试。具体来说,我正在尝试测试方法 onReadAsDataUrl 是否在我的一种方法中从 FileReader 调用。这是我正在测试的示例方法:

loadFinalImage = async (file) => {
  const reader = new FileReader();
  reader.onloadend = () => {
    this.setState({
      imagePreviewUrl: reader.result,
      validCard: true,
    });
  };
  await reader.readAsDataURL(file);
}

这就是我尝试模拟 FileReader 并测试是否调用了 onReadAsDataUrl 的方式:

it('is a valid image and reader.onReadAsDataUrl was called', () => {
    const file = new Blob(['a'.repeat(1)], { type: 'image/png' });
    wrapper = shallow(<ImageUpload />).dive();
    const wrapperInstance = wrapper.instance();
    const mockReader = jest.fn();
    jest.spyOn('FileReader', () => jest.fn());
    FileReader.mockImplementation(() => { return mockReader });
    const onReadAsDataUrl = jest.spyOn(mockReader, 'readAsDataURL');
    wrapperInstance.loadFinalImage(file);
    expect(onReadAsDataUrl).toHaveBeenCalled();
  });

在我 运行: yarn jest 之后,我得到以下测试失败:

Cannot spyOn on a primitive value; string given.

我假设我收到此错误是因为我没有导入 FileReader,但我不确定我将如何导入或模拟它,因为 FileReader 是一个接口。这是测试失败的图像:

我对 jest、reactjs 和 web 开发有点菜鸟,但很想学习如何解决这个问题。到目前为止我看过的一些资源是:Unresolved Shopify Mock of FileReader, , and Mocking FileReader with jasmine.

如有任何帮助,我们将不胜感激!提前谢谢你。

很可能 OP 现在已经找到了答案,但由于我面临着几乎相同的问题,所以我是这样做的 - 从 .

获取输入

我认为@Jackyef 评论是正确的方法,但我认为您建议的 mockImplementation 调用是不正确的。

就我而言,以下事实证明是正确的。

const readAsDataURL = jest
  .spyOn(global, "FileReader")
  .mockImplementation(function() {
    this.readAsDataURL = jest.fn();
  });

值得注意的是,VSCode 强调了匿名函数的潜在重构。它建议:

class (Anonymous function)
(local function)(): void
This constructor function may be converted to a class declaration.ts(80002)

我对 JS 还是比较陌生,所以恐怕我无法解释这是什么意思,也不知道应该做什么重构。

我个人无法使用任何 jest.spyOn() 方法。

使用 jest.spyOn(FileReader.prototype, 'readAsDataURL') 不断产生 Cannot spy the readAsDataURL property because it is not a function; undefined given instead 错误,

jest.spyOn(global, "FileReader").mockImplementation(...) 返回了 Cannot spy the FileReader property because it is not a function; undefined given instead 错误

我使用以下方法成功地模拟了 FileReader 原型:

Object.defineProperty(global, 'FileReader', {
  writable: true,
  value: jest.fn().mockImplementation(() => ({
    readAsDataURL: jest.fn(),
    onLoad: jest.fn()
  })),
})

然后在我的测试中,我能够通过模拟事件并像这样手动触发它来测试文件输入 onChange 方法(它正在使用 FileReader):

const file = {
  size: 1000,
  type: "audio/mp3",
  name: "my-file.mp3"
}
const event = {
  target: {
    files: [file]
  }
}
wrapper.vm.onChange(event)

我希望它可以帮助任何其他调查此问题的人。