// @vitest-environment jsdom import { describe, it, expect, vi, beforeEach } from "vitest"; import { fitWithin, resizeToJpegBase64 } from "./resizeImage"; describe("fitWithin", () => { it("scales down a landscape image so the long edge fits maxEdge", () => { expect(fitWithin(4000, 3000, 2000)).toEqual({ width: 2000, height: 1500 }); }); it("scales down a portrait image so the long edge fits maxEdge", () => { expect(fitWithin(3000, 4000, 2000)).toEqual({ width: 1500, height: 2000 }); }); it("does NOT upscale when both dimensions already fit", () => { expect(fitWithin(800, 600, 2000)).toEqual({ width: 800, height: 600 }); }); it("handles exact fit on one edge", () => { expect(fitWithin(2000, 1000, 2000)).toEqual({ width: 2000, height: 1000 }); }); it("squares stay square ratio", () => { expect(fitWithin(4000, 4000, 2000)).toEqual({ width: 2000, height: 2000 }); }); }); describe("resizeToJpegBase64", () => { it("converts a File to JPEG base64", async () => { const pngBytes = new Uint8Array([ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53, 0xde, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41, 0x54, 0x08, 0xd7, 0x63, 0xf8, 0xcf, 0xc0, 0x00, 0x00, 0x03, 0x01, 0x01, 0x00, 0x18, 0xdd, 0x8d, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, ]); const file = new File([pngBytes], "test.png", { type: "image/png" }); // Mock the browser APIs that jsdom doesn't provide const bitmap = { width: 300, height: 200, close: vi.fn() }; const blob = new Blob(["fake-jpeg-data"], { type: "image/jpeg" }); vi.stubGlobal("createImageBitmap", vi.fn().mockResolvedValue(bitmap)); // Intercept canvas creation via a mock on HTMLCanvasElement const origCreateElement = document.createElement.bind(document); document.createElement = vi.fn((tag: string) => { if (tag === "canvas") { const fakeCanvas: Partial & { toBlob: (cb: (b: Blob | null) => void, t: string) => void } = { width: 0, height: 0, getContext: () => ({ drawImage: () => {}, toBlob: (cb: (b: Blob | null) => void, type: string) => cb(blob) }), toBlob: (cb: (b: Blob | null) => void, type: string) => cb(blob), } as unknown as HTMLCanvasElement; return fakeCanvas; } return origCreateElement(tag); }) as typeof document.createElement; const result = await resizeToJpegBase64(file); expect(result.base.startsWith("data:")).toBe(false); expect(result.fileType).toBe("image/jpeg"); expect(typeof result.bytes).toBe("number"); expect(bitmap.close).toHaveBeenCalled(); document.createElement = origCreateElement; vi.unstubAllGlobals(); }); });