【发布时间】:2022-01-13 08:40:02
【问题描述】:
我在 vue-test-utils 中使用 jest,我想要上传文件的测试方法。 vue文件组件中的这个方法。
async uploadFiles(file){
this.$refs.iconUpload.setAttribute('data-load', 'loading')
let formData = new FormData();
formData.append('image', file);
try{
const result = await fetch('/upload', {
method: 'POST',
body: formData,
})
const data = await result.json();
if(data.status){
this.$refs.iconUpload.setAttribute('data-load', 'success')
this.$refs.btnClear.style.display = 'none';
this.$refs.btnGoBack.style.display = 'none';
this.uploadDone = true;
}else {
this.showSpecialError(this.$refs.elseError)
}
}catch (e){
this.showSpecialError(this.$refs.elseError)
return null
}
}
我想用resolve和reject来测试它
const file = {
size: 500,
type: 'image/png',
name: 'image.png
};
const event = {
target: {
files: [file],
},
};
global.fetch = jest.fn(() => Promise.resolve({
json: () => Promise.resolve({ data })
}));
test('the function of sending the file returns the required response on a successful response', async () => {
const result = await wrapper.vm.uploadFiles(event)
expect(result).toEqual(file)
})
但测试总是返回 null
【问题讨论】:
-
对于初学者来说,fetch 被错误地模拟了。不会有data.status。然后uploadFiles 不返回结果
标签: javascript vue.js jestjs vue-test-utils