File
Blob: tests/worker/lib/parse-body.workers.test.ts
| 1 | import { exports } from "cloudflare:workers"; |
| 2 | import { beforeEach, describe, expect, it } from "vitest"; |
| 3 | |
| 4 | import { bearerFor } from "@tests/worker/helpers/auth"; |
| 5 | import { resetD1Tables } from "@tests/worker/helpers/db"; |
| 6 | import { PROD_ORIGIN } from "@tests/worker/helpers/request"; |
| 7 | import { seedUser, seedWorkspace } from "@tests/worker/helpers/seeds"; |
| 8 | |
| 9 | async function postWithAuth(body: string, userId: string, contentType = "application/json"): Promise<Response> { |
| 10 | const url = new URL("/api/v1/workspaces", PROD_ORIGIN); |
| 11 | const headers = new Headers({ |
| 12 | "content-type": contentType, |
| 13 | authorization: await bearerFor(userId), |
| 14 | }); |
| 15 | return exports.default.fetch( |
| 16 | new Request(url.toString(), { |
| 17 | method: "POST", |
| 18 | headers, |
| 19 | body, |
| 20 | }), |
| 21 | ); |
| 22 | } |
| 23 | |
| 24 | describe("parseBody - malformed JSON", () => { |
| 25 | let userId: string; |
| 26 | |
| 27 | beforeEach(async () => { |
| 28 | await resetD1Tables(); |
| 29 | const user = await seedUser(); |
| 30 | await seedWorkspace({ owner_id: user.id }); |
| 31 | userId = user.id; |
| 32 | }); |
| 33 | |
| 34 | it("returns 400 invalid_json for a malformed body via a parseBody route", async () => { |
| 35 | const res = await postWithAuth("{not-valid-json", userId); |
| 36 | expect(res.status).toBe(400); |
| 37 | const body = (await res.json()) as { error: string; message: string }; |
| 38 | expect(body.error).toBe("invalid_json"); |
| 39 | }); |
| 40 | |
| 41 | it("returns 400 invalid_json for a body that is not JSON at all", async () => { |
| 42 | const res = await postWithAuth("hello", userId, "text/plain"); |
| 43 | expect(res.status).toBe(400); |
| 44 | const body = (await res.json()) as { error: string }; |
| 45 | expect(body.error).toBe("invalid_json"); |
| 46 | }); |
| 47 | |
| 48 | it("returns 400 validation_error for valid JSON that fails schema validation", async () => { |
| 49 | // `null` is valid JSON; CreateWorkspaceRequest expects an object → Zod path, distinct error code. |
| 50 | const res = await postWithAuth("null", userId); |
| 51 | expect(res.status).toBe(400); |
| 52 | const body = (await res.json()) as { error: string }; |
| 53 | expect(body.error).toBe("validation_error"); |
| 54 | }); |
| 55 | }); |