| 1 | type Checks = { |
| 2 | ok(value: boolean, label: string): void; |
| 3 | eq(actual: unknown, expected: unknown, label: string): void; |
| 4 | }; |
| 5 | |
| 6 | export function createFileUploadMock(target: string, { ok, eq }: Checks) { |
| 7 | return (upload: (file: File) => Promise<string>) => { |
| 8 | const previous = globalThis.fetch; |
| 9 | globalThis.fetch = async (input, init = {}) => { |
| 10 | const url = new URL(String(input), "http://localhost/"); |
| 11 | eq(url.pathname, "/__reasonix_attachment_upload", "ordinary file uses the raw upload endpoint"); |
| 12 | eq(url.searchParams.get("target"), target, "upload carries the source attachment target"); |
| 13 | eq(init.method, "POST", "ordinary file upload uses POST"); |
| 14 | ok(init.body instanceof File, "ordinary file upload sends the File directly"); |
| 15 | eq(new Headers(init.headers).get("content-type"), "application/octet-stream", "ordinary file upload uses raw binary content type"); |
| 16 | const file = init.body as File; |
| 17 | eq(url.searchParams.get("name"), file.name, "upload preserves the filename"); |
| 18 | const path = await upload(file); |
| 19 | return new Response(JSON.stringify({ path }), { status: 201, headers: { "content-type": "application/json" } }); |
| 20 | }; |
| 21 | return () => { globalThis.fetch = previous; }; |
| 22 | }; |
| 23 | } |
| 24 | |
| 25 | export function dispatchPasteFile(textarea: HTMLTextAreaElement, file: File) { |
| 26 | const event = new Event("paste", { bubbles: true, cancelable: true }); |
| 27 | Object.defineProperty(event, "clipboardData", { |
| 28 | configurable: true, |
| 29 | value: { files: [file], items: [], types: ["Files"], getData: () => "" }, |
| 30 | }); |
| 31 | textarea.dispatchEvent(event); |
| 32 | } |
| 33 |