validation.ts
This file
Path
test/validation.ts
246 lines · 9.4 KiB · TypeScript
Last changed by
RefactorSindre Sorhusbefore adoptiona5ed57b
History of this fileTake it
Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
line 1why, one step back1import test from 'ava';TweaksSindre Sorhusbefore adoption3ded2aa
line 2why, one step back2import ky, {type ResponsePromise} from '../source/index.js';Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
lines 3–5why, one step back34const okFetch = async () => new Response('ok');5TweaksSindre Sorhusbefore adoption3ded2aa
line 6why, one step back6// `timeout` and `totalTimeout` are documented as milliseconds or `false`. Anything else used to be passed straight to `setTimeout()`, which clamps it to ~1ms, or was silently ignored, so the request never got the timeout the caller asked for. `null` is not accepted either, so it is reported rather than selecting the default.Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
line 7why, one step back7test('rejects non-numeric and negative `timeout` values', async t => {TweaksSindre Sorhusbefore adoption3ded2aa
line 8why, one step back8 for (const timeout of ['1000', Number.NaN, -1, -0.5, {}, null] as unknown[]) {Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
line 9why, one step back9 // eslint-disable-next-line no-await-in-loopTweaksSindre Sorhusbefore adoption3ded2aa
line 10why, one step back10 await t.throwsAsync(ky('https://example.com', {timeout: timeout as never, fetch: okFetch}),Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
lines 11–14why, one step back11 {12 name: 'TypeError',13 message: 'The `timeout` option must be a non-negative number or `false`',14 },Validate the retry options and forward every fetch-only extensionSindre Sorhusbefore adoptiond9774cf
line 15why, one step back15 `timeout: ${JSON.stringify(timeout)}`,Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
lines 16–20why, one step back16 );17 }18});1920test('rejects non-numeric and negative `totalTimeout` values', async t => {TweaksSindre Sorhusbefore adoption3ded2aa
line 21why, one step back21 for (const totalTimeout of ['1000', Number.NaN, -1, -0.5, {}, null] as unknown[]) {Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
line 22why, one step back22 // eslint-disable-next-line no-await-in-loopTweaksSindre Sorhusbefore adoption3ded2aa
line 23why, one step back23 await t.throwsAsync(ky('https://example.com', {totalTimeout: totalTimeout as never, fetch: okFetch}),Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
lines 24–27why, one step back24 {25 name: 'TypeError',26 message: 'The `totalTimeout` option must be a non-negative number or `false`',27 },Validate the retry options and forward every fetch-only extensionSindre Sorhusbefore adoptiond9774cf
line 28why, one step back28 `totalTimeout: ${JSON.stringify(totalTimeout)}`,Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
lines 29–32why, one step back29 );30 }31});32TweaksSindre Sorhusbefore adoption3ded2aa
lines 33–34why, one step back33test('treats an `undefined` timeout as absent', async t => {34 t.is(await ky('https://example.com', {timeout: undefined, totalTimeout: undefined, fetch: okFetch}).text(), 'ok');Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
lines 35–38why, one step back35});3637test('rejects `timeout` and `totalTimeout` above the maximum safe value', async t => {38 for (const option of ['timeout', 'totalTimeout'] as const) {TweaksSindre Sorhusbefore adoption3ded2aa
lines 39–48why, one step back39 for (const value of [2_147_483_648, Number.POSITIVE_INFINITY]) {40 // eslint-disable-next-line no-await-in-loop41 await t.throwsAsync(ky('https://example.com', {[option]: value, fetch: okFetch}),42 {43 instanceOf: RangeError,44 message: `The \`${option}\` option cannot be greater than 2147483647`,45 },46 `${option}: ${value}`,47 );48 }Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
lines 49–51why, one step back49 }50});51Validate the retry options and forward every fetch-only extensionSindre Sorhusbefore adoptiond9774cf
line 52why, one step back52test('accepts `false`, `0` and non-negative numbers for the timeout options', async t => {Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
line 53why, one step back53 t.is(await ky('https://example.com', {timeout: false, totalTimeout: false, fetch: okFetch}).text(), 'ok');Validate the retry options and forward every fetch-only extensionSindre Sorhusbefore adoptiond9774cf
line 54why, one step back54 t.is(await ky('https://example.com', {timeout: 0, totalTimeout: 5000, fetch: async () => new Response('a')}).text(), 'a');Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
lines 55–57why, one step back55});5657test('rejects invalid timeout values set from an `init` hook', async t => {TweaksSindre Sorhusbefore adoption3ded2aa
lines 58–63why, one step back58 await t.throwsAsync(ky('https://example.com', {59 fetch: okFetch,60 hooks: {61 init: [options => {62 options.timeout = 'soon' as never;63 }],Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
line 64why, one step back64 },TweaksSindre Sorhusbefore adoption3ded2aa
lines 65–68why, one step back65 }), {66 name: 'TypeError',67 message: 'The `timeout` option must be a non-negative number or `false`',68 });Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745
line 69why, one step back69});Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569
line 70why, one step back70TweaksSindre Sorhusbefore adoption3ded2aa
lines 71–72why, one step back71// These callbacks are called directly, so a non-function value surfaced as a runtime error naming Ky's own internals (`this[#options].stringifyJson`, `initHookOptions.parseJson`) instead of the option the user set, and only once the request had already been built. The constructor calls `stringifyJson` itself, so that one has to be checked before anything else happens.72test('rejects non-function callback options', async t => {Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569
lines 73–76why, one step back73 for (const [key, value] of [74 ['parseJson', 'x'],75 ['stringifyJson', 5],76 ['fetch', 'x'],TweaksSindre Sorhusbefore adoption3ded2aa
line 77why, one step back77 ['fetch', null],Restore the retry-only marker condition and cover the remaining casesSindre Sorhusbefore adoption692c435
lines 78–79why, one step back78 ['onDownloadProgress', 'x'],79 ['onUploadProgress', 'x'],Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569
lines 80–82why, one step back80 ] as Array<[string, unknown]>) {81 const options: Record<string, unknown> = {[key]: value};82TweaksSindre Sorhusbefore adoption3ded2aa
lines 83–84why, one step back83 // eslint-disable-next-line no-await-in-loop84 await t.throwsAsync(ky('https://example.com', options as never), {Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569
lines 85–90why, one step back85 name: 'TypeError',86 message: `The \`${key}\` option must be a function`,87 }, `${key}: ${JSON.stringify(value)}`);88 }89});90TweaksSindre Sorhusbefore adoption3ded2aa
lines 91–96why, one step back91test('rejects a non-function `stringifyJson` before it is called', async t => {92 await t.throwsAsync(ky.post('https://example.com', {93 json: {a: 1},94 stringifyJson: 'nope' as never,95 fetch: okFetch,96 }), {Check the callbacks before the constructor uses them and reject an array `hooks`Sindre Sorhusbefore adoption16b5936
lines 97–101why, one step back97 name: 'TypeError',98 message: 'The `stringifyJson` option must be a function',99 });100});101TweaksSindre Sorhusbefore adoption3ded2aa
lines 102–103why, one step back102test('rejects a `throwHttpErrors` value that is neither a boolean nor a function', async t => {103 for (const value of ['yes', 1, {}, null] as unknown[]) {Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569
lines 104–108why, one step back104 const options: Record<string, unknown> = {105 throwHttpErrors: value,106 fetch: async () => new Response('server error', {status: 500}),107 };108TweaksSindre Sorhusbefore adoption3ded2aa
lines 109–110why, one step back109 // eslint-disable-next-line no-await-in-loop110 await t.throwsAsync(ky('https://example.com', options as never), {Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569
lines 111–125why, one step back111 name: 'TypeError',112 message: 'The `throwHttpErrors` option must be a boolean or a function',113 }, `throwHttpErrors: ${JSON.stringify(value)}`);114 }115});116117test('accepts a valid `throwHttpErrors` function', async t => {118 const options: Record<string, unknown> = {119 throwHttpErrors: (status: number) => status === 404,120 fetch: async () => new Response('server error', {status: 500}),121 };122123 t.is(await ky('https://example.com', options as never).text(), 'server error');124});125TweaksSindre Sorhusbefore adoption3ded2aa
lines 126–127why, one step back126// The `input` type check ran after the options were built, so a nullish input dereferenced `.headers` first and reported an internal TypeError instead of the option the caller got wrong.127test('a nullish or non-string `input` reports the input error', async t => {Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569
line 128why, one step back128 for (const input of [null, undefined, 5, {}, true] as unknown[]) {TweaksSindre Sorhusbefore adoption3ded2aa
lines 129–130why, one step back129 // eslint-disable-next-line no-await-in-loop130 await t.throwsAsync(ky(input as never, {fetch: okFetch}), {Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569
lines 131–135why, one step back131 name: 'TypeError',132 message: '`input` must be a string, URL, or Request',133 }, `input: ${String(input)}`);134 }135});Type-check `onDownloadProgress` before the request is sentSindre Sorhusbefore adoption6e27594
line 136why, one step back136TweaksSindre Sorhusbefore adoption3ded2aa
lines 137–138why, one step back137// `onDownloadProgress` was type-checked at the very end of the pipeline, so an invalid value ran the whole request and only then reported the typo, leaving the response body with nobody able to release it.138test('rejects a non-function `onDownloadProgress` before the request is sent', async t => {Type-check `onDownloadProgress` before the request is sentSindre Sorhusbefore adoption6e27594
lines 139–141why, one step back139 let fetchCalled = false;140 let beforeRequestCalls = 0;141TweaksSindre Sorhusbefore adoption3ded2aa
lines 142–154why, one step back142 await t.throwsAsync(ky('https://example.com', {143 onDownloadProgress: 'x' as never,144 retry: 0,145 hooks: {146 beforeRequest: [() => {147 beforeRequestCalls++;148 }],149 },150 async fetch() {151 fetchCalled = true;152 return new Response('ok');153 },154 }), {Type-check `onDownloadProgress` before the request is sentSindre Sorhusbefore adoption6e27594
lines 155–160why, one step back155 name: 'TypeError',156 message: 'The `onDownloadProgress` option must be a function',157 });158159 t.false(fetchCalled);160 t.is(beforeRequestCalls, 0);TweaksSindre Sorhusbefore adoption3ded2aa
lines 161–193why, one step back161});162163// `ky()` returns a promise, so errors while setting up the request reject it, the same way `fetch()` reports them, instead of also throwing synchronously.164test('setup errors reject the returned promise and every body method', async t => {165 const setups: Array<[string, unknown, Record<string, unknown>]> = [166 ['invalid option', 'https://example.com', {timeout: -1}],167 ['invalid input', 42, {}],168 ['invalid merged option', 'https://example.com', {hooks: 'none'}],169 ['throwing `init` hook', 'https://example.com', {170 hooks: {171 init: [() => {172 throw new Error('init failed');173 }],174 },175 }],176 ];177178 for (const [label, input, options] of setups) {179 let responsePromise: ResponsePromise | undefined;180 t.notThrows(() => {181 responsePromise = ky(input as never, {...options, fetch: okFetch});182 }, `${label}`);183184 // eslint-disable-next-line no-await-in-loop185 const error = await t.throwsAsync(responsePromise!, undefined, `${label}`);186187 for (const method of ['json', 'text', 'arrayBuffer', 'blob', 'formData'] as const) {188 // eslint-disable-next-line no-await-in-loop189 t.is(await t.throwsAsync(responsePromise![method]()), error, `${label}: ${method}`);190 }191 }192});193RefactorSindre Sorhusbefore adoptiona5ed57b
lines 194–205why, one step back194test('setup errors also reject `.bytes()` with the same error', async t => {195 if (typeof (Response.prototype as unknown as {bytes?: unknown}).bytes !== 'function') {196 t.pass();197 return;198 }199200 const responsePromise = ky('https://example.com', {timeout: -1, fetch: okFetch});201 const error = await t.throwsAsync(responsePromise);202203 t.is(await t.throwsAsync(responsePromise.bytes()), error);204});205TweaksSindre Sorhusbefore adoption3ded2aa
lines 206–227why, one step back206// Option merging only checked `hooks` when it was an object, and replaced an invalid `retry`, so a later layer hid a `null` or another bad shape instead of reporting it.207test('rejects a bad `hooks` or `retry` while merging, before a later layer can hide it', async t => {208 for (const hooks of [null, 'nope', []] as unknown[]) {209 t.throws(() => ky.create({hooks: hooks as never}), {210 instanceOf: TypeError,211 message: 'The `hooks` option must be an object',212 }, `hooks: ${JSON.stringify(hooks)}`);213 }214215 for (const retry of [null, 'nope', []] as unknown[]) {216 t.throws(() => ky.create({retry: retry as never}), {217 instanceOf: TypeError,218 message: '`retry` must be a number or an object',219 }, `retry: ${JSON.stringify(retry)}`);220 }221222 await t.throwsAsync(ky.extend({fetch: okFetch})('https://example.com', {hooks: null as never}), {223 name: 'TypeError',224 message: 'The `hooks` option must be an object',225 });226});227Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d
lines 228–237why, one step back228test('rejects `null` for `referrer` and `referrerPolicy`', async t => {229 for (const key of ['referrer', 'referrerPolicy']) {230 // eslint-disable-next-line no-await-in-loop231 await t.throwsAsync(ky('https://example.com', {[key]: null, fetch: okFetch} as never), {232 name: 'TypeError',233 message: `The \`${key}\` option must not be \`null\`. Use \`undefined\` to clear it.`,234 });235 }236});237TweaksSindre Sorhusbefore adoption3ded2aa
lines 238–245why, one step back238test('rejects a `retry.retryOnTimeout` that is not a boolean', async t => {239 for (const retryOnTimeout of [null, 'false', 0] as unknown[]) {240 // eslint-disable-next-line no-await-in-loop241 await t.throwsAsync(ky('https://example.com', {retry: {retryOnTimeout: retryOnTimeout as never}, fetch: okFetch}), {242 name: 'TypeError',243 message: '`retry.retryOnTimeout` must be a boolean',244 }, `retryOnTimeout: ${JSON.stringify(retryOnTimeout)}`);245 }Type-check `onDownloadProgress` before the request is sentSindre Sorhusbefore adoption6e27594
line 246why, one step back246});