From a68cfda9490023bd0453e0d48bc01eeca785ca3e Mon Sep 17 00:00:00 2001 From: Tanguy Krotoff Date: Fri, 2 Dec 2022 16:05:58 +0100 Subject: [PATCH] Response.bodyUsed should be false when there is no body --- src/body.js | 4 ++-- test/response.js | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/body.js b/src/body.js index 714e27ec4..b7a53263f 100644 --- a/src/body.js +++ b/src/body.js @@ -196,8 +196,6 @@ async function consumeBody(data) { throw new TypeError(`body used already for: ${data.url}`); } - data[INTERNALS].disturbed = true; - if (data[INTERNALS].error) { throw data[INTERNALS].error; } @@ -209,6 +207,8 @@ async function consumeBody(data) { return Buffer.alloc(0); } + data[INTERNALS].disturbed = true; + /* c8 ignore next 3 */ if (!(body instanceof Stream)) { return Buffer.alloc(0); diff --git a/test/response.js b/test/response.js index b5157623f..fa074cff4 100644 --- a/test/response.js +++ b/test/response.js @@ -264,4 +264,24 @@ describe('Response', () => { new Response('a').data; })); + + it('should set bodyUsed to true if body has been read', async () => { + for (const toCheck of ['a', '']) { + const res = new Response(toCheck); + expect(res.bodyUsed).to.equal(false); + + expect(await res.text()).to.equal(toCheck); + expect(res.bodyUsed).to.equal(true); + } + }); + + it('should not change bodyUsed if nothing to read', async () => { + for (const toCheck of [undefined, null]) { + const res = new Response(toCheck); + expect(res.bodyUsed).to.equal(false); + + expect(await res.text()).to.equal(''); + expect(res.bodyUsed).to.equal(false); + } + }); });