Search code examples
javascriptvue.jsvitevitesthappy-dom

Vitest - FormData is not a constructor problem with test unit


I'm using Vistest for the test unit in a proyect with Vue + Vite. I have a helper for upload images to Cloudinary, the problem is when run the test, Vitest return this error in console

Ocurrio un error al intentar subir la imagen TypeError: FormData is not a constructor

This is my helper

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;

And this is the test

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);
  });
});

The constructor is right, it's capitalize. Also I change the environment for "happy-dom" in the file vite.config.js


Solution

  • happy-dom doesn't have FormData class, you have to mock that:

    // 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;
    
    

    If you don't want to mock FormData, you could use jsdom.


    I found a similar problem with jest and react:

    FormData is not defined in React Jest

    A last thing, if you want to test the content of the FormData you could implement a simple FormData class.

    Also check this: Testing FormData submitted to fetch using jest