Skip to content
Myr

validation.ts

This file

Path

test/validation.ts

246 lines · 9.4 KiB · TypeScript

Last changed by

RefactorSindre Sorhusbefore adoptiona5ed57b

History of this file

Take it

Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745

line 1why, one step back
1import test from 'ava';

TweaksSindre Sorhusbefore adoption3ded2aa

line 2why, one step back
2import ky, {type ResponsePromise} from '../source/index.js';

Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745

lines 3–5why, one step back
3
4const okFetch = async () => new Response('ok');5

TweaksSindre Sorhusbefore adoption3ded2aa

line 6why, one step back
6// `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 back
7test('rejects non-numeric and negative `timeout` values', async t => {

TweaksSindre Sorhusbefore adoption3ded2aa

line 8why, one step back
8 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 back
9 // eslint-disable-next-line no-await-in-loop

TweaksSindre Sorhusbefore adoption3ded2aa

line 10why, one step back
10 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 back
11 {
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 back
15 `timeout: ${JSON.stringify(timeout)}`,

Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745

lines 16–20why, one step back
16 );
17 }18});1920test('rejects non-numeric and negative `totalTimeout` values', async t => {

TweaksSindre Sorhusbefore adoption3ded2aa

line 21why, one step back
21 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 back
22 // eslint-disable-next-line no-await-in-loop

TweaksSindre Sorhusbefore adoption3ded2aa

line 23why, one step back
23 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 back
24 {
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 back
28 `totalTimeout: ${JSON.stringify(totalTimeout)}`,

Reject invalid `timeout` and `totalTimeout` valuesSindre Sorhusbefore adoptionf446745

lines 29–32why, one step back
29 );
30 }31});32

TweaksSindre Sorhusbefore adoption3ded2aa

lines 33–34why, one step back
33test('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 back
35});
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 back
39 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 back
49 }
50});51

Validate the retry options and forward every fetch-only extensionSindre Sorhusbefore adoptiond9774cf

line 52why, one step back
52test('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 back
53 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 back
54 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 back
55});
5657test('rejects invalid timeout values set from an `init` hook', async t => {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 58–63why, one step back
58 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 back
64 },

TweaksSindre Sorhusbefore adoption3ded2aa

lines 65–68why, one step back
65 }), {
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 back
69});

Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569

line 70why, one step back
70

TweaksSindre Sorhusbefore adoption3ded2aa

lines 71–72why, one step back
71// 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 back
73 for (const [key, value] of [
74 ['parseJson', 'x'],75 ['stringifyJson', 5],76 ['fetch', 'x'],

TweaksSindre Sorhusbefore adoption3ded2aa

line 77why, one step back
77 ['fetch', null],

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

lines 78–79why, one step back
78 ['onDownloadProgress', 'x'],
79 ['onUploadProgress', 'x'],

Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569

lines 80–82why, one step back
80 ] as Array<[string, unknown]>) {
81 const options: Record<string, unknown> = {[key]: value};82

TweaksSindre Sorhusbefore adoption3ded2aa

lines 83–84why, one step back
83 // eslint-disable-next-line no-await-in-loop
84 await t.throwsAsync(ky('https://example.com', options as never), {

Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569

lines 85–90why, one step back
85 name: 'TypeError',
86 message: `The \`${key}\` option must be a function`,87 }, `${key}: ${JSON.stringify(value)}`);88 }89});90

TweaksSindre Sorhusbefore adoption3ded2aa

lines 91–96why, one step back
91test('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 back
97 name: 'TypeError',
98 message: 'The `stringifyJson` option must be a function',99 });100});101

TweaksSindre Sorhusbefore adoption3ded2aa

lines 102–103why, one step back
102test('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 back
104 const options: Record<string, unknown> = {
105 throwHttpErrors: value,106 fetch: async () => new Response('server error', {status: 500}),107 };108

TweaksSindre Sorhusbefore adoption3ded2aa

lines 109–110why, one step back
109 // eslint-disable-next-line no-await-in-loop
110 await t.throwsAsync(ky('https://example.com', options as never), {

Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569

lines 111–125why, one step back
111 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});125

TweaksSindre Sorhusbefore adoption3ded2aa

lines 126–127why, one step back
126// 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 back
128 for (const input of [null, undefined, 5, {}, true] as unknown[]) {

TweaksSindre Sorhusbefore adoption3ded2aa

lines 129–130why, one step back
129 // eslint-disable-next-line no-await-in-loop
130 await t.throwsAsync(ky(input as never, {fetch: okFetch}), {

Validate the callbacks and the inputSindre Sorhusbefore adoption6b67569

lines 131–135why, one step back
131 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 back
136

TweaksSindre Sorhusbefore adoption3ded2aa

lines 137–138why, one step back
137// `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 back
139 let fetchCalled = false;
140 let beforeRequestCalls = 0;141

TweaksSindre Sorhusbefore adoption3ded2aa

lines 142–154why, one step back
142 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 back
155 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 back
161});
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});193

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 194–205why, one step back
194test('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});205

TweaksSindre Sorhusbefore adoption3ded2aa

lines 206–227why, one step back
206// 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});227

Report the sent request for a hook's response, and finish the cross-realm and `null` checksSindre Sorhusbefore adoption7f0137d

lines 228–237why, one step back
228test('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});237

TweaksSindre Sorhusbefore adoption3ded2aa

lines 238–245why, one step back
238test('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 back
246});