From fbb3c88f3c4f6948abfc7b347648cd80fd43fbfb Mon Sep 17 00:00:00 2001 From: Yury Semikhatsky Date: Thu, 11 Nov 2021 11:12:24 -0800 Subject: [PATCH] fix(fetch): smarter JSON.stringify for application/json requests (#10245) --- packages/playwright-core/src/client/fetch.ts | 24 ++++++-- packages/playwright-core/src/server/fetch.ts | 16 +++++- tests/global-fetch.spec.ts | 60 ++++++++++++++++++++ 3 files changed, 94 insertions(+), 6 deletions(-) diff --git a/packages/playwright-core/src/client/fetch.ts b/packages/playwright-core/src/client/fetch.ts index 970c22d11d..2f74bdfe2d 100644 --- a/packages/playwright-core/src/client/fetch.ts +++ b/packages/playwright-core/src/client/fetch.ts @@ -142,14 +142,18 @@ export class APIRequestContext extends ChannelOwner { + const request = await playwright.request.newContext(); + const [req] = await Promise.all([ + server.waitForRequest('/empty.html'), + request.post(server.EMPTY_PAGE, { + headers: { + 'content-type': 'application/json' + }, + data: value + }) + ]); + const body = await req.postBody; + expect(body.toString()).toEqual(stringifiedValue); + await request.dispose(); + }); + + it(`should not double stringify ${type} body when content-type is application/json`, async ({ playwright, server }) => { + const request = await playwright.request.newContext(); + const [req] = await Promise.all([ + server.waitForRequest('/empty.html'), + request.post(server.EMPTY_PAGE, { + headers: { + 'content-type': 'application/json' + }, + data: stringifiedValue + }) + ]); + const body = await req.postBody; + expect(body.toString()).toEqual(stringifiedValue); + await request.dispose(); + }); +} + +it(`should accept already serialized data as Buffer when content-type is application/json`, async ({ playwright, server }) => { + const request = await playwright.request.newContext(); + const value = JSON.stringify(JSON.stringify({ 'foo': 'bar' })); + const [req] = await Promise.all([ + server.waitForRequest('/empty.html'), + request.post(server.EMPTY_PAGE, { + headers: { + 'content-type': 'application/json' + }, + data: Buffer.from(value, 'utf8') + }) + ]); + const body = await req.postBody; + expect(body.toString()).toEqual(value); + await request.dispose(); +});