Skip to content
Myr

response-consumption.ts

This file

Path

test/response-consumption.ts

262 lines · 8.8 KiB · TypeScript

Last changed by

Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435

History of this file

Take it

More testsSindre Sorhusbefore adoptioncd1dba0

lines 1–183why, one step back
1import test from 'ava';
2import ky, {HTTPError} from '../source/index.js';3import {createHttpTestServer} from './helpers/create-http-test-server.js';45const binary = Buffer.from([0, 255, 128, 13, 10, 0, 195, 40]);67// Fetch's Body mixin consumes bytes without text decoding for these methods.8// https://fetch.spec.whatwg.org/#body-mixin9for (const method of ['arrayBuffer', 'blob', 'bytes'] as const) {10 const run = method === 'bytes' && typeof Response.prototype.bytes !== 'function' ? test.skip : test;11 run(`${method} preserves non-text bytes through download progress`, async t => {12 const server = await createHttpTestServer(t);13 server.get('/', (_request, response) => {14 response.set({'content-type': 'application/octet-stream', 'content-length': String(binary.length)}).end(binary);15 });16 const chunks: Uint8Array[] = [];17 let finalTransferred = 0;18 const result = await ky(server.url, {19 onDownloadProgress(progress, chunk) {20 chunks.push(chunk);21 finalTransferred = progress.transferredBytes;22 },23 })[method]();24 if (method === 'blob') {25 t.true(result instanceof Blob);26 } else if (method === 'arrayBuffer') {27 t.true(result instanceof ArrayBuffer);28 } else {29 t.true(result instanceof Uint8Array);30 }3132 const bytes = result instanceof Blob ? new Uint8Array(await result.arrayBuffer()) : new Uint8Array(result);33 t.deepEqual(Buffer.from(bytes), binary);34 t.deepEqual(Buffer.concat(chunks), binary);35 t.is(finalTransferred, binary.length);36 if (result instanceof Blob) {37 t.is(result.type, 'application/octet-stream');38 t.is(result.size, binary.length);39 }40 });41}4243test('formData parses URL-encoded repeated fields, plus signs, and UTF-8 through progress', async t => {44 const server = await createHttpTestServer(t);45 const text = 'tag=one&tag=two&message=caf%C3%A9+time&literal=%2B&empty=';46 server.get('/', (_request, response) => {47 response.set('content-type', 'application/x-www-form-urlencoded').end(text);48 });49 const chunks: Uint8Array[] = [];50 const form = await ky(server.url, {51 onDownloadProgress(_progress, chunk) {52 chunks.push(chunk);53 },54 }).formData();5556 t.deepEqual(form.getAll('tag'), ['one', 'two']);57 t.is(form.get('message'), 'café time');58 t.is(form.get('literal'), '+');59 t.is(form.get('empty'), '');60 t.is(Buffer.concat(chunks).toString(), text);61});6263test('formData parses multipart file bytes and repeated fields', async t => {64 const server = await createHttpTestServer(t);65 const form = new FormData();66 form.append('tag', 'one');67 form.append('tag', 'two');68 form.append('file', new Blob([binary], {type: 'application/octet-stream'}), 'sample.bin');69 const encoded = new Response(form);70 const body = Buffer.from(await encoded.arrayBuffer());71 server.get('/', (_request, response) => {72 response.set('content-type', encoded.headers.get('content-type')!).end(body);73 });74 const parsed = await ky(server.url).formData();75 const file = parsed.get('file') as File;7677 t.deepEqual(parsed.getAll('tag'), ['one', 'two']);78 t.true(file instanceof File);79 t.is(file.name, 'sample.bin');80 t.is(file.type, 'application/octet-stream');81 t.deepEqual(Buffer.from(await file.arrayBuffer()), binary);82});8384test('formData rejects unsupported response media types without retrying', async t => {85 const server = await createHttpTestServer(t);86 let requests = 0;87 server.get('/', (_request, response) => {88 requests++;89 response.set('content-type', 'application/json').end('{}');90 });9192 await t.throwsAsync(ky(server.url).formData(), {instanceOf: TypeError});93 t.is(requests, 1);94});9596for (const firstMethod of ['text', 'json', 'arrayBuffer'] as const) {97 test(`${firstMethod} shortcut consumes the shared response exactly once`, async t => {98 const server = await createHttpTestServer(t);99 let requests = 0;100 server.get('/', (_request, response) => {101 requests++;102 response.json({value: 42});103 });104 const pending = ky(server.url);105 await pending[firstMethod]();106 const response = await pending;107108 t.true(response.bodyUsed);109 await t.throwsAsync(pending.text(), {instanceOf: TypeError});110 t.throws(() => response.clone(), {instanceOf: TypeError});111 t.is(requests, 1);112 });113}114115test('redirected progress clones retain metadata and use their own parser response context', async t => {116 const server = await createHttpTestServer(t);117 server.get('/start', (_request, response) => {118 response.redirect('/end');119 });120 server.get('/end', (_request, response) => {121 response.set('x-final', 'yes').json({value: 42});122 });123 const parserResponses: Response[] = [];124 const chunks: Uint8Array[] = [];125 const response = await ky(`${server.url}/start`, {126 parseJson(text, context) {127 parserResponses.push(context.response);128 return JSON.parse(text);129 },130 onDownloadProgress(_progress, chunk) {131 chunks.push(chunk);132 },133 });134 const clone = response.clone().clone();135136 t.is(clone.url, `${server.url}/end`);137 t.true(clone.redirected);138 t.is(clone.headers.get('x-final'), 'yes');139 t.deepEqual(await clone.json(), {value: 42});140 t.false(response.bodyUsed);141 t.deepEqual(await response.json(), {value: 42});142 t.is(parserResponses.length, 2);143 t.is(parserResponses[0], clone);144 t.is(parserResponses[1], response);145 t.is(Buffer.concat(chunks).toString(), '{"value":42}');146});147148// JSON texts can contain primitive values, including falsy ones (RFC 8259 §3).149// https://www.rfc-editor.org/rfc/rfc8259.html#section-3150for (const value of [false, true, 0, '', ['one', 2]]) {151 test(`JSON value ${JSON.stringify(value)} is preserved in successful and error responses`, async t => {152 const server = await createHttpTestServer(t);153 const text = JSON.stringify(value);154 server.get('/success', (_request, response) => {155 response.set('content-type', 'application/json').end(text);156 });157 server.get('/error', (_request, response) => {158 response.status(422).set('content-type', 'application/json').end(text);159 });160161 t.deepEqual(await ky(`${server.url}/success`).json(), value);162 const error = await t.throwsAsync(ky(`${server.url}/error`), {instanceOf: HTTPError});163 t.deepEqual(error.data, value);164 });165}166167test('disabling HTTP errors allows consuming a binary error response without JSON parsing', async t => {168 const server = await createHttpTestServer(t);169 let parserCalls = 0;170 server.get('/', (_request, response) => {171 response.status(422).set('content-type', 'application/octet-stream').end(binary);172 });173 const buffer = await ky(server.url, {174 throwHttpErrors: false,175 parseJson() {176 parserCalls++;177 return {};178 },179 }).arrayBuffer();180181 t.deepEqual(Buffer.from(buffer), binary);182 t.is(parserCalls, 0);183});

Run beforeError hooks for body reader failuresSindre Sorhusbefore adoption323b98f

lines 184–236why, one step back
184
185test('formData parsing errors pass through beforeError exactly once without retrying', async t => {186 const server = await createHttpTestServer(t);187 let requests = 0;188 server.get('/', (_request, response) => {189 requests++;190 response.set('content-type', 'application/json').end('{}');191 });192 const replacement = new Error('Unexpected response format');193 let hookCalls = 0;194195 await t.throwsAsync(ky(server.url, {196 hooks: {197 beforeError: [({error, request, retryCount}) => {198 hookCalls++;199 t.true(error instanceof TypeError);200 t.is(request.url, `${server.url}/`);201 t.is(retryCount, 0);202 return replacement;203 }],204 },205 }).formData(), {is: replacement});206 t.is(hookCalls, 1);207 t.is(requests, 1);208});209210test('beforeError failures while handling body-reader errors propagate without running hooks again', async t => {211 const readError = new Error('Response body could not be read');212 const hookError = new Error('Error handler failed');213 let fetchCalls = 0;214 let hookCalls = 0;215216 await t.throwsAsync(ky('https://example.com', {217 async fetch() {218 fetchCalls++;219 return new Response(new ReadableStream({220 start(controller) {221 controller.error(readError);222 },223 }));224 },225 hooks: {226 beforeError: [({error}) => {227 hookCalls++;228 t.is(error, readError);229 throw hookError;230 }],231 },232 }).text(), {is: hookError});233234 t.is(fetchCalls, 1);235 t.is(hookCalls, 1);236});

Resolve leftover `replaceOption()` wrappers, name the request behind a response, and advertise the media typesSindre Sorhusbefore adoptiona0eeae2

line 237why, one step back
237

Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569

lines 238–239why, one step back
238// The media type each shortcut advertises is deliberately narrow, so a caller that wants another representation asks for it through `headers` instead.
239test('each body shortcut advertises exactly one media type', async t => {

Resolve leftover `replaceOption()` wrappers, name the request behind a response, and advertise the media typesSindre Sorhusbefore adoptiona0eeae2

lines 240–241why, one step back
240 const accepts: Record<string, string | undefined> = {};
241

Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435

line 242why, one step back
242 for (const type of ['json', 'text', 'formData', 'arrayBuffer', 'blob', 'bytes'] as const) {

Resolve leftover `replaceOption()` wrappers, name the request behind a response, and advertise the media typesSindre Sorhusbefore adoptiona0eeae2

lines 243–252why, one step back
243 // eslint-disable-next-line no-await-in-loop
244 await ky('https://example.com', {245 retry: 0,246 async fetch(request) {247 accepts[type] = request.headers.get('accept') ?? undefined;248 return new Response('x', {headers: {'content-type': 'application/json'}});249 },250 })[type]().catch(() => undefined);251 }252

Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569

lines 253–258why, one step back
253 t.deepEqual(accepts, {
254 json: 'application/json',255 text: 'text/*',256 formData: 'multipart/form-data',257 arrayBuffer: '*/*',258 blob: '*/*',

Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435

lines 259–260why, one step back
259 // Only exposed when the runtime implements `Response.prototype.bytes()`.
260 bytes: typeof Response.prototype.bytes === 'function' ? '*/*' : undefined,

Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569

line 261why, one step back
261 });

Resolve leftover `replaceOption()` wrappers, name the request behind a response, and advertise the media typesSindre Sorhusbefore adoptiona0eeae2

line 262why, one step back
262});