6 changed files with 154 additions and 32 deletions
@ -0,0 +1,75 @@ |
|||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; |
||||
|
import { splitWithDimensions } from "../gridSplitter"; |
||||
|
import { uploadBlobToGatewayMedia } from "@/utils/gatewayMediaUpload"; |
||||
|
|
||||
|
vi.mock("@/utils/gatewayMediaUpload", () => ({ |
||||
|
uploadBlobToGatewayMedia: vi.fn(async () => ({ url: "https://media.example/split.png" })), |
||||
|
})); |
||||
|
|
||||
|
class MockImage { |
||||
|
width = 100; |
||||
|
height = 100; |
||||
|
onload: (() => void) | null = null; |
||||
|
onerror: (() => void) | null = null; |
||||
|
|
||||
|
set src(_value: string) { |
||||
|
queueMicrotask(() => this.onload?.()); |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
function mockCanvas() { |
||||
|
return { |
||||
|
width: 0, |
||||
|
height: 0, |
||||
|
getContext: vi.fn(() => ({ |
||||
|
drawImage: vi.fn(), |
||||
|
})), |
||||
|
toBlob: vi.fn((callback: (blob: Blob | null) => void) => { |
||||
|
callback(new Blob(["split"], { type: "image/png" })); |
||||
|
}), |
||||
|
} as unknown as HTMLCanvasElement; |
||||
|
} |
||||
|
|
||||
|
describe("gridSplitter", () => { |
||||
|
const originalCreateElement = document.createElement.bind(document); |
||||
|
|
||||
|
beforeEach(() => { |
||||
|
vi.clearAllMocks(); |
||||
|
vi.stubGlobal("Image", MockImage); |
||||
|
vi.stubGlobal("fetch", vi.fn(async () => ({ |
||||
|
ok: true, |
||||
|
blob: async () => new Blob(["source"], { type: "image/png" }), |
||||
|
}))); |
||||
|
vi.stubGlobal("URL", { |
||||
|
...URL, |
||||
|
createObjectURL: vi.fn(() => "blob:canvas-safe-source"), |
||||
|
revokeObjectURL: vi.fn(), |
||||
|
}); |
||||
|
vi.spyOn(document, "createElement").mockImplementation((tagName: string) => { |
||||
|
if (tagName === "canvas") return mockCanvas(); |
||||
|
return originalCreateElement(tagName); |
||||
|
}); |
||||
|
}); |
||||
|
|
||||
|
afterEach(() => { |
||||
|
vi.unstubAllGlobals(); |
||||
|
vi.restoreAllMocks(); |
||||
|
}); |
||||
|
|
||||
|
it("loads remote images through the media proxy before canvas splitting", async () => { |
||||
|
const result = await splitWithDimensions("https://remote.example/grid.png", 1, 1); |
||||
|
|
||||
|
expect(fetch).toHaveBeenCalledWith( |
||||
|
`/api/proxy-media?url=${encodeURIComponent("https://remote.example/grid.png")}` |
||||
|
); |
||||
|
expect(URL.createObjectURL).toHaveBeenCalled(); |
||||
|
expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:canvas-safe-source"); |
||||
|
expect(uploadBlobToGatewayMedia).toHaveBeenCalledWith( |
||||
|
expect.any(Blob), |
||||
|
expect.stringMatching(/^grid-cell-\d+-1\.png$/), |
||||
|
"image/png", |
||||
|
"image" |
||||
|
); |
||||
|
expect(result.images).toEqual(["https://media.example/split.png"]); |
||||
|
}); |
||||
|
}); |
||||
Loading…
Reference in new issue