vue.js Vitest - FormData不是测试单元的构造函数问题

blmhpbnm  于 2022-12-19  发布在  Vue.js
关注(0)|答案(1)|浏览(227)

我正在使用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”的环境

bfhwhh0e

bfhwhh0e1#

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
我在jest and react中发现了类似的问题:
FormData is not defined in React Jest
最后,如果您想测试FormData的内容,可以实现一个简单的FormData类。
还请检查以下内容:Testing FormData submitted to fetch using jest

相关问题