From 890e5f36f57fe3cacf33714cdbebc2bd2fed506b Mon Sep 17 00:00:00 2001 From: SachaCR Date: Thu, 21 May 2020 23:02:43 +0200 Subject: [PATCH] Handle case where the RequestInit object body is null --- ...tractMethodAndBodyFromRequestInitObject.ts | 16 +++++++----- src/test.ts | 26 +++++++++++++++++++ 2 files changed, 35 insertions(+), 7 deletions(-) diff --git a/src/extractMethodAndBodyFromRequestInitObject.ts b/src/extractMethodAndBodyFromRequestInitObject.ts index 334fedc..beeb78e 100644 --- a/src/extractMethodAndBodyFromRequestInitObject.ts +++ b/src/extractMethodAndBodyFromRequestInitObject.ts @@ -10,19 +10,21 @@ export function extractMethodAndBodyFromRequestInitObject( let originalBody = "{}"; if (init) { - if (typeof init.body !== "string") { - throw new Error( - "Sorry Denock only support stringified JSON as body in RequestInit object", - ); - } - originalMethod = init.method ? init.method.toUpperCase() : originalMethod; if (!acceptedMethods.includes(originalMethod)) { throw new Error("Sorry Denock does not support this method"); } - originalBody = init.body; + if (init.body) { + if (typeof init.body !== "string") { + throw new Error( + "Sorry Denock only support stringified JSON as body in RequestInit object", + ); + } + + originalBody = init.body; + } } return { diff --git a/src/test.ts b/src/test.ts index e24582f..2c63b6e 100644 --- a/src/test.ts +++ b/src/test.ts @@ -171,3 +171,29 @@ Deno.test( assertEquals(status, 201); }, ); + +Deno.test( + "denock : Should handle when there is no body in the RequestInit object", + async () => { + denock({ + method: "GET", + protocol: "https", + host: "jsonplaceholder.typicode.com", + path: "/todos", + responseBody: { test: "6" }, + replyStatus: 200, + }); + + const urlObject = new URL("https://jsonplaceholder.typicode.com/todos"); + + const response = await fetch(urlObject, { + method: "GET", + }); + + const body = await response.json(); + const status = response.status; + + assertEquals(body, { test: "6" }); + assertEquals(status, 200); + }, +);