【问题标题】:Vitest - FormData is not a constructor problem with test unitVitest - FormData 不是测试单元的构造函数问题
【发布时间】:2022-07-04 11:15:30
【问题描述】:

我在一个带有 Vue + Vite 的项目中使用 Vistest 作为测试单元。我有一个将图像上传到 Cloudinary 的助手,问题是运行测试时,Vitest 在控制台中返回此错误

Ocurrio un error al intentar subir la imagen TypeError: FormData is 不是构造函数

这是我的助手

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”的环境@

【问题讨论】:

    标签: javascript vue.js vite vitest


    【解决方案1】:

    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;
    
    

    我在 jest 和 react 中发现了类似的问题:

    FormData is not defined in React Jest

    最后一件事,如果你想测试FormData 的内容,你可以实现一个简单的 FormData 类。

    还要检查这个: Testing FormData submitted to fetch using jest

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-23
      • 2017-09-15
      • 1970-01-01
      • 2017-11-19
      相关资源
      最近更新 更多