From 0703318d3bb6cc1340614612d2ae14b23f651242 Mon Sep 17 00:00:00 2001 From: Baptiste Marchand Date: Wed, 2 Mar 2022 02:26:39 +0100 Subject: [PATCH] Fix encoding with json `responseType` (#1996) --- source/core/response.ts | 2 +- test/encoding.ts | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 test/encoding.ts diff --git a/source/core/response.ts b/source/core/response.ts index a6e66b5fd..413dcad4a 100644 --- a/source/core/response.ts +++ b/source/core/response.ts @@ -138,7 +138,7 @@ export const parseBody = (response: Response, responseType: ResponseType, parseJ } if (responseType === 'json') { - return rawBody.length === 0 ? '' : parseJson(rawBody.toString()); + return rawBody.length === 0 ? '' : parseJson(rawBody.toString(encoding)); } if (responseType === 'buffer') { diff --git a/test/encoding.ts b/test/encoding.ts new file mode 100644 index 000000000..8e6b1d68e --- /dev/null +++ b/test/encoding.ts @@ -0,0 +1,19 @@ +import {Buffer} from 'buffer'; +import test from 'ava'; +import withServer from './helpers/with-server.js'; + +test('encoding works with json', withServer, async (t, server, got) => { + const json = {data: 'é'}; + + server.get('/', (_request, response) => { + response.set('Content-Type', 'application-json'); + response.send(Buffer.from(JSON.stringify(json), 'latin1')); + }); + + const response = await got('', { + encoding: 'latin1', + responseType: 'json', + }); + + t.deepEqual(response.body, json); +});