|
| 1 | +import test from "node:test"; |
| 2 | +import assert from "node:assert/strict"; |
| 3 | +import { createApp } from "../app.js"; |
| 4 | + |
| 5 | +async function withServer(run) { |
| 6 | + const app = createApp(); |
| 7 | + const server = app.listen(0); |
| 8 | + |
| 9 | + await new Promise((resolve, reject) => { |
| 10 | + server.once("listening", resolve); |
| 11 | + server.once("error", reject); |
| 12 | + }); |
| 13 | + |
| 14 | + try { |
| 15 | + const { port } = server.address(); |
| 16 | + await run(`http://127.0.0.1:${port}`); |
| 17 | + } finally { |
| 18 | + await new Promise((resolve, reject) => { |
| 19 | + server.close((error) => (error ? reject(error) : resolve())); |
| 20 | + }); |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +test("POST /api/uploads rejects requests without a file", async () => { |
| 25 | + await withServer(async (baseUrl) => { |
| 26 | + const response = await fetch(`${baseUrl}/api/uploads`, { |
| 27 | + method: "POST", |
| 28 | + }); |
| 29 | + const payload = await response.json(); |
| 30 | + |
| 31 | + assert.equal(response.status, 400); |
| 32 | + assert.deepEqual(payload, { |
| 33 | + success: false, |
| 34 | + message: "File is required", |
| 35 | + }); |
| 36 | + }); |
| 37 | +}); |
| 38 | + |
| 39 | +test("POST /api/uploads still accepts a file upload", async () => { |
| 40 | + await withServer(async (baseUrl) => { |
| 41 | + const form = new FormData(); |
| 42 | + form.append("file", new Blob(["hello"], { type: "text/plain" }), "hello.txt"); |
| 43 | + |
| 44 | + const response = await fetch(`${baseUrl}/api/uploads`, { |
| 45 | + method: "POST", |
| 46 | + body: form, |
| 47 | + }); |
| 48 | + const payload = await response.json(); |
| 49 | + |
| 50 | + assert.equal(response.status, 201); |
| 51 | + assert.deepEqual(payload, { |
| 52 | + success: true, |
| 53 | + data: { |
| 54 | + filename: "hello.txt", |
| 55 | + status: "uploaded", |
| 56 | + }, |
| 57 | + }); |
| 58 | + }); |
| 59 | +}); |
0 commit comments