2026-05-02 13:02:57 +08:00

40 lines
1.5 KiB
TypeScript

import { afterEach, expect, test, vi } from "vitest";
import { setAccessToken } from "@/shared/api/request";
import { uploadFile, uploadImage } from "@/shared/api/upload";
afterEach(() => {
setAccessToken("");
vi.unstubAllGlobals();
});
test("uploadImage sends multipart data to generated image endpoint", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response(JSON.stringify({ code: 0, data: { url: "https://media.haiyihy.com/admin/images/a.png" } })))
);
const result = await uploadImage(new File(["image"], "avatar.png", { type: "image/png" }));
const [url, init] = vi.mocked(fetch).mock.calls[0];
expect(result.url).toContain("/admin/images/");
expect(String(url)).toContain("/api/v1/admin/files/image/upload");
expect(init?.method).toBe("POST");
expect(init?.body).toBeInstanceOf(FormData);
expect(init?.headers).not.toHaveProperty("Content-Type");
});
test("uploadFile sends multipart data to generated file endpoint", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response(JSON.stringify({ code: 0, data: { url: "https://media.haiyihy.com/admin/files/a.pdf" } })))
);
await uploadFile(new File(["file"], "doc.pdf", { type: "application/pdf" }));
const [url, init] = vi.mocked(fetch).mock.calls[0];
expect(String(url)).toContain("/api/v1/admin/files/upload");
expect(init?.method).toBe("POST");
expect(init?.body).toBeInstanceOf(FormData);
expect(init?.headers).not.toHaveProperty("Content-Type");
});