我使用Vistest作为测试单元,在带有Vue + Vite的proyect中。我有一个将图像上传到Cloudinary的助手,问题是当运行测试时,Vitest在控制台中返回此错误
Ocurrio un error al intentar subir la imagen TypeError: FormData不是构造函数
这是我的帮手
import axios from "axios";
const uploadImage = async (file) => {
if (!file) return;
try {
const formData = new FormData();
const objData = {
file,
upload_preset: "journal-vue",
};
Object.entries(objData).forEach(([key, value]) => {
formData.append(key, value);
});
const url = "https://api.cloudinary.com/v1_1/christian-door/image/upload";
const { data } = await axios.post(url, formData);
return data.secure_url;
} catch (error) {
console.log("Ocurrio un error al intentar subir la imagen", error);
return null;
}
};
export default uploadImage;这就是测试
import uploadImage from "@/modules/journal/helpers/uploadImage.js";
import axios from "axios";
describe("Test in helper uploadImage", () => {
test("Must be upload a file and return an url", async () => {
const url =
"https://res.cloudinary.com/christian-door/image/upload/v1653891463/fas3px2zm7eq8gt6mfaw.jpg";
const { data } = await axios.get(url, { responseType: "arraybuffer" });
const file = new File([data], "image.jpg");
const urc = await uploadImage(file);
console.log(urc);
});
});构造函数是正确的,它是大写的。此外,我还在文件vite.config.js中更改了“高兴-dom”的环境。
发布于 2022-07-04 03:15:30
happy-dom没有FormData类,您必须模拟:
// vitest.setup.ts
class FormDataMock {
append: (name: string, value: string | Blob, fileName?: string) => void = vitest.fn();
delete: (name: string) => void = vitest.fn();
get: (name: string) => FormDataEntryValue | null = vitest.fn();
getAll: (name: string) => FormDataEntryValue[] = vitest.fn();
has: (name: string) => boolean = vitest.fn();
set: (name: string, value: string | Blob, fileName?: string) => void = vitest.fn();
forEach: (callbackfn: (value: FormDataEntryValue, key: string, parent: FormData) => void, thisArg?: any) => void = vitest.fn();
}
// @ts-ignore
global.FormData = FormDataMock;如果不想模仿FormData,可以使用jsdom。
我发现了一个类似的问题,开玩笑,并作出反应:
FormData is not defined in React Jest
最后一件事是,如果您想测试FormData的内容,可以实现一个简单的FormData类。
https://stackoverflow.com/questions/72510621
复制相似问题