Skip to content
Myr

response-handling.ts

This file

Path

test/response-handling.ts

309 lines · 10.5 KiB · TypeScript

Last changed by

RefactorSindre Sorhusbefore adoptiona5ed57b

History of this file

Take it

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1–309why, one step back
1import test from 'ava';
2import ky, {3 ResponseSizeError,4 SchemaValidationError,5 type Progress,6 type StandardSchemaV1,7} from '../source/index.js';89const url = 'https://example.com/data';10const encoder = new TextEncoder();11const invalidSchemaMessage = 'The `schema` argument must follow the Standard Schema specification';1213const createChunkedBody = (chunks: string[]) => new ReadableStream<Uint8Array>({14 start(controller) {15 for (const chunk of chunks) {16 controller.enqueue(encoder.encode(chunk));17 }1819 controller.close();20 },21});2223// A body that was partly read through a reader and then released is used but no longer locked, so only `bodyUsed` tells the wrappers to leave it alone.24const createReleasedResponse = async (): Promise<Response> => {25 const response = new Response(createChunkedBody(['first', 'second']));26 const reader = response.body!.getReader();27 await reader.read();28 reader.releaseLock();29 return response;30};3132// A `content-length` that is not a size must be treated as an unknown total rather than turning `percent` negative or `NaN`.33for (const contentLength of ['-10', 'not-a-number']) {34 test(`download progress treats a content-length of ${contentLength} as an unknown total`, async t => {35 const progressEvents: Progress[] = [];36 const text = await ky(url, {37 retry: 0,38 fetch: async () => new Response(createChunkedBody(['ab', 'cd']), {headers: {'content-length': contentLength}}),39 onDownloadProgress(progress) {40 progressEvents.push(progress);41 },42 }).text();4344 t.is(text, 'abcd');45 t.deepEqual(progressEvents, [46 {percent: 0, totalBytes: 0, transferredBytes: 2},47 {percent: 1, totalBytes: 4, transferredBytes: 4},48 ]);49 });50}5152test('upload progress treats a negative declared content-length as an unknown total', async t => {53 const progressEvents: Progress[] = [];54 await ky.post(url, {55 body: createChunkedBody(['ab', 'cd']),56 headers: {'content-length': '-10'},57 retry: 0,58 async fetch(request) {59 await (request as Request).arrayBuffer();60 return new Response('ok');61 },62 onUploadProgress(progress) {63 progressEvents.push(progress);64 },65 }).text();6667 t.deepEqual(progressEvents, [68 {percent: 0, totalBytes: 0, transferredBytes: 2},69 {percent: 1, totalBytes: 4, transferredBytes: 4},70 ]);71});7273// Chromium replaces the size error with a generic TypeError in native body methods, so the wrappers restore it. Node.js passes the stream error through on the first read, so a second read, which natively fails with "Body is unusable", is the only way to make the native method fail with something else here. The tests below use it to check that each wrapper restores the size error.74test('a body read after the size limit was exceeded reports the size error again', async t => {75 const response = await ky(url, {76 retry: 0,77 maxResponseSize: 1,78 fetch: async () => new Response('too large'),79 });8081 const firstError = await t.throwsAsync(response.text(), {instanceOf: ResponseSizeError});82 // The native method now fails with "Body is unusable", which hides why the body is gone.83 const secondError = await t.throwsAsync(response.arrayBuffer(), {instanceOf: ResponseSizeError});84 t.is(secondError, firstError);85});8687// The download progress wrapper sits on top of the limited body, so it has to inherit the size error of the body it wraps.88test('a body read after the size limit was exceeded reports the size error again with download progress', async t => {89 const response = await ky(url, {90 retry: 0,91 maxResponseSize: 1,92 onDownloadProgress: () => undefined,93 fetch: async () => new Response('too large'),94 });9596 const firstError = await t.throwsAsync(response.text(), {instanceOf: ResponseSizeError});97 const secondError = await t.throwsAsync(response.text(), {instanceOf: ResponseSizeError});98 t.is(secondError, firstError);99});100101test('a clone keeps reporting the size error after its body failed', async t => {102 const response = await ky(url, {103 retry: 0,104 maxResponseSize: 1,105 fetch: async () => new Response('too large'),106 });107108 const clone = response.clone();109 const firstError = await t.throwsAsync(clone.text(), {instanceOf: ResponseSizeError});110 const secondError = await t.throwsAsync(clone.text(), {instanceOf: ResponseSizeError});111 t.is(secondError, firstError);112});113114// The `afterResponse` hook gets a clone of the limited response, and returning it wraps it in a second limit. That outer limit never sees the bytes past the inner one, so it has to report the inner error.115test('a response returned by an afterResponse hook reports the size error of the limit it already went through', async t => {116 const response = await ky(url, {117 retry: 0,118 maxResponseSize: 1,119 fetch: async () => new Response('too large'),120 hooks: {121 afterResponse: [({response}) => response],122 },123 });124125 const firstError = await t.throwsAsync(response.text(), {instanceOf: ResponseSizeError});126 const secondError = await t.throwsAsync(response.text(), {instanceOf: ResponseSizeError});127 t.is(secondError, firstError);128});129130for (const [label, options] of [131 ['with `maxResponseSize`', {maxResponseSize: 1000}],132 ['with `onDownloadProgress`', {onDownloadProgress: () => undefined}],133] as Array<[string, Record<string, unknown>]>) {134 test(`a partly read and released body reports the native error ${label}`, async t => {135 const response = await ky(url, {136 ...options,137 retry: 0,138 fetch: createReleasedResponse,139 });140141 await t.throwsAsync(response.text(), {142 name: 'TypeError',143 message: 'Body is unusable: Body has already been read',144 });145 });146}147148for (const [label, takeBody] of [149 ['locked by a reader', (request: Request) => {150 request.body!.getReader();151 }],152 ['partly read and released', async (request: Request) => {153 const reader = request.body!.getReader();154 await reader.read();155 reader.releaseLock();156 }],157] as Array<[string, (request: Request) => void | Promise<void>]>) {158 test(`upload progress leaves a request body that is ${label} to the native error`, async t => {159 const run = async (onUploadProgress?: () => void) => t.throwsAsync(ky.post(url, {160 body: 'payload',161 retry: 0,162 onUploadProgress,163 fetch: async input => new Response(await (input as Request).text()),164 hooks: {165 beforeRequest: [async ({request}) => {166 await takeBody(request);167 }],168 },169 }).text());170171 const withoutProgress = await run();172 const withProgress = await run(() => undefined);173174 t.truthy(withoutProgress?.message);175 t.is(withProgress?.message, withoutProgress?.message);176 });177}178179for (const [label, standard] of [180 ['`null`', null],181 ['a function with a `validate` method', Object.assign(() => undefined, {version: 1, vendor: 'test', validate: (value: unknown) => ({value})})],182] as Array<[string, unknown]>) {183 test(`.json(schema) rejects a \`~standard\` property that is ${label}`, async t => {184 await t.throwsAsync(ky(url, {185 retry: 0,186 fetch: async () => Response.json({value: 1}),187 }).json({'~standard': standard} as unknown as StandardSchemaV1), {188 instanceOf: TypeError,189 message: invalidSchemaMessage,190 });191 });192}193194// A Standard Schema result signals failure by having `issues` at all, so an empty list is still a failure rather than a success without a `value`.195test('.json(schema) treats an empty issues list as a validation failure', async t => {196 const error = await t.throwsAsync(ky(url, {197 retry: 0,198 fetch: async () => Response.json({value: 1}),199 }).json({200 '~standard': {201 version: 1,202 vendor: 'test',203 validate: () => ({issues: []}),204 },205 }), {instanceOf: SchemaValidationError});206207 t.deepEqual(error?.issues, []);208});209210test('a clone made after a retry of an earlier attempt response keeps the request of that attempt for parseJson', async t => {211 const sent: Request[] = [];212 const parseJsonRequests: Request[] = [];213 let firstAttemptClone: Response | undefined;214215 const data = await ky(url, {216 retry: {limit: 1, delay: () => 0},217 async fetch(request) {218 sent.push(request as Request);219 return sent.length === 1 ? Response.json({attempt: 1}, {status: 500}) : Response.json({attempt: 2});220 },221 parseJson(text, {request}) {222 parseJsonRequests.push(request);223 return JSON.parse(text);224 },225 hooks: {226 afterResponse: [({response}) => {227 firstAttemptClone ??= response.clone();228 }],229 },230 }).json();231232 t.deepEqual(data, {attempt: 2});233 t.is(sent.length, 2);234 parseJsonRequests.length = 0;235236 // Cloned only now, after the second attempt became the request that was sent last.237 t.deepEqual(await firstAttemptClone!.clone().json(), {attempt: 1});238 t.deepEqual(parseJsonRequests, [sent[0]]);239});240241// With retries enabled, the hook gets the clone prepared for the next attempt rather than the request that was sent, so releasing that clone once the request settles must spare a response built on its body.242test('an afterResponse hook can return the body of the request it was given as the response', async t => {243 const text = await ky.post(url, {244 body: 'echo-payload',245 retry: {limit: 2},246 fetch: async () => new Response('from fetch'),247 hooks: {248 afterResponse: [({request}) => new Response(request.body)],249 },250 }).text();251252 t.is(text, 'echo-payload');253});254255// With retries enabled, `ky.request` is the clone prepared for the next attempt by the time the response arrives, which is not the request that produced it.256test('response.json() gives parseJson the request that was sent', async t => {257 let sent: Request | undefined;258 let parseJsonRequest: Request | undefined;259260 const response = await ky(url, {261 retry: {limit: 2},262 async fetch(request) {263 sent = request as Request;264 return Response.json({value: 1});265 },266 parseJson(text, {request}) {267 parseJsonRequest = request;268 return JSON.parse(text) as unknown;269 },270 });271272 t.deepEqual(await response.json(), {value: 1});273 t.is(parseJsonRequest, sent);274});275276test('the .json() shortcut uses a parseJson set by an init hook', async t => {277 const parsedTexts: string[] = [];278279 const data = await ky(url, {280 retry: 0,281 fetch: async () => Response.json({value: 1}),282 hooks: {283 init: [options => {284 options.parseJson = text => {285 parsedTexts.push(text);286 return {parsedBy: 'init hook'};287 };288 }],289 },290 }).json();291292 t.deepEqual(data, {parsedBy: 'init hook'});293 t.deepEqual(parsedTexts, ['{"value":1}']);294});295296test('response.json() with parseJson consumes the body like the native method', async t => {297 const response = await ky(url, {298 retry: 0,299 fetch: async () => Response.json({value: 1}),300 parseJson: text => JSON.parse(text) as unknown,301 });302303 t.deepEqual(await response.json(), {value: 1});304 t.true(response.bodyUsed);305 await t.throwsAsync(response.json(), {306 name: 'TypeError',307 message: 'Body is unusable: Body has already been read',308 });309});