Skip to content

Commit

Permalink
feat(response): set content-length header for empty response (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
christoph-fricke authored Jun 23, 2024
1 parent 8fe655e commit f08acf1
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/real-carpets-rhyme.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 4 additions & 0 deletions src/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,13 @@ export function createResponseHelper<
};

const empty: EmptyResponse<typeof status> = (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<null>;
};

Expand Down
30 changes: 30 additions & 0 deletions test/response-content.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit f08acf1

Please sign in to comment.