Skip to content

Commit 0b6b981

Browse files
authored
fix: Request without a body should not throw an error (#49)
fixes #48
1 parent c11b7c8 commit 0b6b981

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

src/util.js

+11-2
Original file line numberDiff line numberDiff line change
@@ -94,18 +94,27 @@ export function parseUrl(url) {
9494
* @param {Request} request The request to read the body from.
9595
* @returns {Promise<string|any|FormData|null>} The body of the request.
9696
*/
97-
export function getBody(request) {
97+
export async function getBody(request) {
98+
9899
// first get the content type
99100
const contentType = request.headers.get("content-type");
100101

101102
// if there's no content type, there's no body
102103
if (!contentType) {
103104
return Promise.resolve(null);
105+
}
106+
107+
// next try to read the body as text to see if there's a body
108+
const text = await request.clone().text();
109+
110+
// if there's no body, return null
111+
if (!text) {
112+
return Promise.resolve(null);
104113
}
105114

106115
// if it's a text format then return a string
107116
if (contentType.startsWith("text")) {
108-
return request.text();
117+
return text;
109118
}
110119

111120
// if the content type is JSON, parse the body as JSON

tests/mock-server.test.js

+23
Original file line numberDiff line numberDiff line change
@@ -563,6 +563,29 @@ describe("MockServer", () => {
563563
"application/json",
564564
);
565565
});
566+
567+
it("should return response when JSON request is sent without a body", async () => {
568+
server.post("/test", {
569+
status: 200,
570+
body: { foo: "bar" },
571+
});
572+
573+
const request = createRequest({
574+
method: "POST",
575+
url: `${BASE_URL}/test`,
576+
headers: {
577+
"content-type": "application/json",
578+
},
579+
});
580+
581+
const { response } = await server.traceReceive(request);
582+
assert.strictEqual(response.status, 200);
583+
assert.strictEqual(response.statusText, "OK");
584+
assert.strictEqual(
585+
response.headers.get("content-type"),
586+
"application/json",
587+
);
588+
});
566589
});
567590

568591
describe("Query Strings", () => {

0 commit comments

Comments
 (0)