diff --git a/.changeset/real-carpets-rhyme.md b/.changeset/real-carpets-rhyme.md new file mode 100644 index 0000000..fbf101f --- /dev/null +++ b/.changeset/real-carpets-rhyme.md @@ -0,0 +1,5 @@ +--- +"openapi-msw": minor +--- + +Added "content-length" header for `response(...).empty()`. If no "content-length" header is provided in the response init, the "content-length" header is now set with the value "0". See #56 for more details. diff --git a/src/response.ts b/src/response.ts index 1e44973..6f6fe5a 100644 --- a/src/response.ts +++ b/src/response.ts @@ -91,9 +91,13 @@ export function createResponseHelper< }; const empty: EmptyResponse = (init) => { + const headers = new Headers(init?.headers); + if (!headers.has("content-length")) headers.set("content-length", "0"); + return new HttpResponse(null, { status: status as number, ...init, + headers, }) as StrictResponse; }; diff --git a/test/response-content.test.ts b/test/response-content.test.ts index 8bc88e1..a57bb91 100644 --- a/test/response-content.test.ts +++ b/test/response-content.test.ts @@ -88,6 +88,36 @@ describe("Given an OpenAPI schema endpoint with response content", () => { expect(result?.response?.status).toBe(204); }); + test("When an empty response is created, Then the response includes a content-length header", async () => { + const request = new Request(new URL("/resource", "http://localhost:3000"), { + method: "get", + }); + + const handler = http.get("/resource", ({ response }) => { + return response(204).empty(); + }); + const result = await handler.run({ request }); + + expect(result?.response?.status).toBe(204); + expect(result?.response?.headers.has("content-length")).toBeTruthy(); + expect(result?.response?.headers.get("content-length")).toBe("0"); + }); + + test("When an empty response with content-length is created, Then the provided content-length header is used", async () => { + const request = new Request(new URL("/resource", "http://localhost:3000"), { + method: "get", + }); + + const handler = http.get("/resource", ({ response }) => { + return response(204).empty({ headers: { "content-length": "32" } }); + }); + const result = await handler.run({ request }); + + expect(result?.response?.status).toBe(204); + expect(result?.response?.headers.has("content-length")).toBeTruthy(); + expect(result?.response?.headers.get("content-length")).toBe("32"); + }); + test("When the response helper is used for wildcard status codes, Then a specific response status must be chosen", async () => { const request = new Request(new URL("/resource", "http://localhost:3000"), { method: "get",