在过去的几周里,我一直在努力使用 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
是一个接口(interface)。这是测试失败的图像:
我对 Jest 、reactjs 和 Web 开发有点菜鸟,但很想学习如何解决这个问题。到目前为止我看过的一些资源是:Unresolved Shopify Mock of FileReader , How to mock a new function in jest ,和 Mocking FileReader with jasmine .
任何帮助将不胜感激!预先感谢您。
最佳答案
我个人无法让任何 jest.spyOn() 方法发挥作用。
使用 jest.spyOn(FileReader.prototype, 'readAsDataURL')
不断生成 Cannot sply the readAsDataURL property because it is not a function;未定义给定而不是
错误,
和 jest.spyOn(global, "FileReader").mockImplementation(...)
返回了一个 无法监视 FileReader 属性,因为它不是函数;未定义给定
错误
我成功地使用以下方法模拟了 FileReader 原型(prototype):
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)
我希望它可以帮助其他人研究这个问题。
关于javascript - 如何用 Jest 来模拟 FileReader?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58331840/