error-data.ts
This file
Path
test/error-data.ts
240 lines · 8.1 KiB · TypeScript
Last changed by
RefactorSindre Sorhusbefore adoptiona5ed57b
History of this fileTake it
RefactorSindre Sorhusbefore adoptiona5ed57b
lines 1–240why, one step back1import test, {type ExecutionContext} from 'ava';2import ky, {HTTPError, type Options} from '../source/index.js';34const mebibyte = 1024 * 1024;56const errorResponse = (body: BodyInit | undefined, contentType?: string, status = 400): Response => new Response(body, {7 status,8 headers: contentType === undefined ? {} : {'content-type': contentType},9});1011const getHttpError = async (t: ExecutionContext, response: Response, options: Options = {}): Promise<HTTPError> => {12 const error = await t.throwsAsync(ky('https://example.com', {13 retry: 0,14 async fetch() {15 return response;16 },17 ...options,18 }), {instanceOf: HTTPError});1920 return error!;21};2223const getErrorData = async (t: ExecutionContext, body: BodyInit | undefined, contentType?: string): Promise<unknown> => {24 const error = await getHttpError(t, errorResponse(body, contentType));25 return error.data;26};2728// Yields `chunkCount` chunks of `chunkSize` bytes followed by an optional tail chunk, and records pulls and cancellation.29const createChunkedStream = ({chunkCount, chunkSize, tailSize = 0}: {chunkCount: number; chunkSize: number; tailSize?: number}) => {30 const state = {pulls: 0, cancelled: false};31 let sentChunks = 0;32 let sentTail = false;33 const stream = new ReadableStream<Uint8Array>({34 pull(controller) {35 state.pulls++;36 if (sentChunks < chunkCount) {37 sentChunks++;38 controller.enqueue(new Uint8Array(chunkSize).fill(0x61));39 return;40 }4142 if (tailSize > 0 && !sentTail) {43 sentTail = true;44 controller.enqueue(new Uint8Array(tailSize).fill(0x61));45 return;46 }4748 controller.close();49 },50 cancel() {51 state.cancelled = true;52 },53 });5455 return {stream, state};56};5758const latin1Cafe = Uint8Array.from([0x63, 0x61, 0x66, 0xE9]);5960test('error data is undefined when chunks add up to one byte over the 10 MiB cap', async t => {61 const {stream} = createChunkedStream({chunkCount: 10, chunkSize: mebibyte, tailSize: 1});62 t.is(await getErrorData(t, stream, 'text/plain'), undefined);63});6465test('exceeding the error data cap cancels the response stream', async t => {66 const {stream, state} = createChunkedStream({chunkCount: 1000, chunkSize: mebibyte});67 t.is(await getErrorData(t, stream, 'text/plain'), undefined);68 t.true(state.cancelled);69 t.true(state.pulls < 20);70});7172test('error data is parsed as JSON for the application/x-json subtype', async t => {73 t.deepEqual(await getErrorData(t, '{"error":"subtype"}', 'application/x-json'), {error: 'subtype'});74});7576test('error data is parsed as JSON when the media type is uppercase', async t => {77 t.deepEqual(await getErrorData(t, '{"error":"uppercase"}', 'APPLICATION/PROBLEM+JSON'), {error: 'uppercase'});78});7980test('error data is parsed as JSON when whitespace precedes the parameters', async t => {81 t.deepEqual(await getErrorData(t, '{"error":"spaced"}', 'application/json ; charset=utf-8'), {error: 'spaced'});82});8384test('error data ignores a parameter whose name only ends in charset', async t => {85 t.is(await getErrorData(t, 'café', 'text/plain; xcharset=utf-16le'), 'café');86});8788test('error data uses a charset that follows other parameters', async t => {89 t.is(await getErrorData(t, latin1Cafe, 'text/plain; format=flowed; charset=iso-8859-1'), 'café');90});9192test('error data allows whitespace around the charset equals sign', async t => {93 t.is(await getErrorData(t, latin1Cafe, 'text/plain; charset = iso-8859-1'), 'café');94});9596test('error data charset ends at the comma of a combined content-type header', async t => {97 const headers = new Headers();98 headers.append('content-type', 'text/plain; charset=iso-8859-1');99 headers.append('content-type', 'text/plain');100 const error = await getHttpError(t, new Response(latin1Cafe, {status: 400, headers}));101 t.is(error.data, 'café');102});103104test('error data decodes invalid UTF-8 with replacement characters when no charset is given', async t => {105 t.is(await getErrorData(t, Uint8Array.from([0x61, 0xFF, 0x62]), 'text/plain'), 'a�b');106});107108test('error data is undefined and HTTPError is still thrown when the body stream fails after partial data', async t => {109 const body = new ReadableStream<Uint8Array>({110 start(controller) {111 controller.enqueue(new TextEncoder().encode('partial'));112 },113 pull(controller) {114 controller.error(new Error('connection reset'));115 },116 });117118 t.is(await getErrorData(t, body, 'text/plain'), undefined);119});120121test('error data is undefined when a response without a body stream fails to read text', async t => {122 const response = errorResponse('unused', 'text/plain');123 Object.defineProperty(response, 'body', {value: null});124 Object.defineProperty(response, 'text', {125 async value() {126 throw new TypeError('body unavailable');127 },128 });129130 const error = await getHttpError(t, response);131 t.is(error.data, undefined);132});133134test('error.options is a frozen snapshot without Ky-only size and timeout options', async t => {135 const error = await getHttpError(t, errorResponse('bad', 'text/plain'), {136 method: 'post',137 context: {tag: 'value'},138 timeout: 5000,139 totalTimeout: 60_000,140 maxResponseSize: mebibyte,141 throwHttpErrors: true,142 });143144 t.true(Object.isFrozen(error.options));145 t.is(error.options.method, 'POST');146 t.deepEqual(error.options.context, {tag: 'value'});147 for (const key of ['timeout', 'totalTimeout', 'maxResponseSize', 'throwHttpErrors', 'fetch']) {148 t.false(Object.hasOwn(error.options, key), key);149 }150});151152test('the throwHttpErrors predicate is not called for successful responses', async t => {153 const statuses: number[] = [];154 const response = await ky('https://example.com', {155 retry: 0,156 throwHttpErrors(status) {157 statuses.push(status);158 return true;159 },160 async fetch() {161 return new Response('ok', {status: 201});162 },163 });164165 t.is(await response.text(), 'ok');166 t.deepEqual(statuses, []);167});168169test('the throwHttpErrors predicate is not called for opaque responses', async t => {170 let calls = 0;171 const response = await ky('https://example.com', {172 retry: 0,173 throwHttpErrors() {174 calls++;175 throw new Error('The predicate must not be called');176 },177 async fetch() {178 const response = new Response(undefined);179 Object.defineProperty(response, 'type', {value: 'opaque'});180 Object.defineProperty(response, 'ok', {value: false});181 Object.defineProperty(response, 'status', {value: 0});182 return response;183 },184 });185186 t.is(response.status, 0);187 t.is(calls, 0);188});189190test('error data is undefined and HTTPError is still thrown when a custom parseJson throws synchronously', async t => {191 let parseJsonCallCount = 0;192 const error = await getHttpError(t, errorResponse('{"error":"bad"}', 'application/json'), {193 parseJson() {194 parseJsonCallCount++;195 throw new SyntaxError('Unexpected token');196 },197 });198199 t.is(error.data, undefined);200 t.is(parseJsonCallCount, 1);201});202203test('a custom parseJson is not called for an empty JSON error body', async t => {204 let parseJsonCallCount = 0;205 const error = await getHttpError(t, errorResponse('', 'application/json'), {206 parseJson() {207 parseJsonCallCount++;208 return {parsed: true};209 },210 });211212 t.is(error.data, undefined);213 t.is(parseJsonCallCount, 0);214});215216test('a falsy value from a custom parseJson is kept as the error data', async t => {217 for (const value of [0, false, '']) {218 // eslint-disable-next-line no-await-in-loop219 const error = await getHttpError(t, errorResponse('{"error":"bad"}', 'application/json'), {220 parseJson: () => value,221 });222223 t.is(error.data, value);224 }225});226227// `Headers` joins repeated values with a comma. Ky checks the text before the first `;` for a JSON subtype, so without parameters the last media type decides, which agrees with how the Fetch standard extracts a MIME type from a combined header.228for (const [first, second, expected] of [229 ['application/json', 'application/json', {error: 'combined'}],230 ['text/plain', 'application/json', {error: 'combined'}],231 ['application/json', 'text/plain', '{"error":"combined"}'],232] as const) {233 test(`error data for a combined \`${first}, ${second}\` content-type header`, async t => {234 const headers = new Headers();235 headers.append('content-type', first);236 headers.append('content-type', second);237 const error = await getHttpError(t, new Response('{"error":"combined"}', {status: 400, headers}));238 t.deepEqual(error.data, expected);239 });240}