我正在使用Vistest进行Vue + Vite项目中的测试单元。我有一个上传图像到Cloudinary的助手,问题是运行测试时,Vitest在控制台中返回此错误
图像下出现意图错误类型错误: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
文件中“happy-dom”的环境
1条答案
按热度按时间bfhwhh0e1#
happy-dom
没有FormData类,您必须对此进行模拟:如果不想模拟FormData,可以使用
jsdom
。我在jest and react中发现了类似的问题:
FormData is not defined in React Jest
最后,如果您想测试
FormData
的内容,可以实现一个简单的FormData类。还请检查以下内容:Testing FormData submitted to fetch using jest