Skip to content

Commit

Permalink
Handle case where the RequestInit object body is null
Browse files Browse the repository at this point in the history
  • Loading branch information
SachaCR committed May 21, 2020
1 parent 3a859f2 commit 890e5f3
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/extractMethodAndBodyFromRequestInitObject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
26 changes: 26 additions & 0 deletions src/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
},
);

0 comments on commit 890e5f3

Please sign in to comment.