I'm currently taking a Udemy course on React, but I'm using vitest and TypeScript instead of Jest and JavaScript.
I'm encountering an issue with a fileUpload
utility that uploads images to Cloudinary. While it works fine in the app, I'm facing an error when attempting to test the function. Cloudinary responds with the following error message: {"error":{"message":"Upload preset must be specified when using unsigned upload"}}
.
fileUpload.ts
export const fileUpload = async (file?: File) => {
if (!file) throw new Error("There's no file selected for uploading");
const cloudinaryCloudName = "dwalcv9li";
const cloudUrl = `https://api.cloudinary.com/v1_1/${cloudinaryCloudName}/upload`;
const formData = new FormData();
formData.append("upload_preset", "react-course");
formData.append("file", file);
try {
const resp = await fetch(cloudUrl, {
method: "POST",
body: formData,
});
const responseBody = await resp.text();
console.log({ responseBody });
if (!resp.ok) throw new Error("It was not posible to update the image");
const cloudResp = await resp.json();
return cloudResp.secure_url;
} catch (error: unknown) {
if (error instanceof Error) {
console.log(error.message);
throw new Error(error.message);
} else {
console.log(error);
}
}
};
fileUpload.test.ts
import { describe, expect, it } from "vitest";
import { fileUpload } from "./fileUpload";
describe("fileUpload", () => {
it("should throw an error if no file is selected", async () => {
await expect(fileUpload()).rejects.toThrowError(
"There's no file selected for uploading"
);
});
it.only("should upload a file to Cloudinary successfully", async () => {
const imageUrl =
"https://images.unsplash.com/photo-1506744038136-46273834b3fb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxleHBsb3JlLWZlZWR8MXx8fGVufDB8fHx8&w=1000&q=80";
const resp = await fetch(imageUrl);
const blob = await resp.blob();
const file = new File([blob], "foto.jpg");
const result = await fileUpload(file);
expect(typeof result).toBe("string");
});
});
vite.config.ts
/// <reference types="vitest" />
/// <reference types="vite/client" />
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
test: {
globals: true,
environment: "jsdom",
},
});
I have tried different approaches found in internet, but none of them really are about the issue I'm facing. I also tried another fetch get functions and they work, is just when I use formData that it don't seem to work.