From 0451560555f8432749b9928a10e96d28969939ae Mon Sep 17 00:00:00 2001 From: Yudu Date: Thu, 24 Aug 2023 08:30:16 +0800 Subject: [PATCH] fix: resolve duplex error when fetching with stream body --- src/patch/fetch.ts | 7 +++++-- tests/fetch-stream-body.spec.ts | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 tests/fetch-stream-body.spec.ts diff --git a/src/patch/fetch.ts b/src/patch/fetch.ts index abdc558..1af2240 100644 --- a/src/patch/fetch.ts +++ b/src/patch/fetch.ts @@ -124,9 +124,12 @@ const Xhook: typeof fetch = function (input, init = { headers: {} }) { } }; - const send = () => { + const send = async () => { const { url, isFetch, acceptedRequest, ...restInit } = options; - Native(url, restInit) + if (input instanceof Request && restInit.body instanceof ReadableStream) { + restInit.body = await new Response(restInit.body).text(); + } + return Native(url, restInit) .then(response => processAfter(response)) .catch(function (err) { fullfiled = reject; diff --git a/tests/fetch-stream-body.spec.ts b/tests/fetch-stream-body.spec.ts new file mode 100644 index 0000000..b1c8b44 --- /dev/null +++ b/tests/fetch-stream-body.spec.ts @@ -0,0 +1,21 @@ +import { test, expect } from "@playwright/test"; + +test("fetch with stream body should not throw errors", async ({ page }) => { + await page.goto("http://127.0.0.1:8080/example/common.html"); + const res = await page.evaluate(async () => { + return new Promise(resolve => { + const req = new Request("example1.txt", { + method: "POST", + body: "{}", + }); + fetch(req) + .then(res => { + resolve(true); + }) + .catch(err => { + resolve(false); + }); + }); + }); + expect(res).toEqual(true); +});