Skip to content
Myr

request-construction.ts

This file

Path

test/request-construction.ts

404 lines · 14.8 KiB · TypeScript

Last changed by

Fix CISindre Sorhusbefore adoptiond9ddb03

History of this file

Take it

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1–324why, one step back
1import test from 'ava';
2import ky from '../source/index.js';34// Each test sends the request to a custom `fetch` that records it, so no server is needed.5const createRecordingFetch = () => {6 const requests: Request[] = [];7 const inits: Array<Record<string, unknown>> = [];89 const fetch = async (request: Request, init: Record<string, unknown>) => {10 requests.push(request);11 inits.push(init);12 return new Response('ok');13 };1415 return {fetch: fetch as unknown as typeof globalThis.fetch, requests, inits};16};1718// The URL parser removes a tab or newline anywhere in the input, so `h\rttps:` is still the `https:` scheme and must be rejected like `h\tttps:`.19test('baseUrl rejects a slashless HTTP URL with a carriage return inside the scheme', async t => {20 const {fetch, requests} = createRecordingFetch();2122 for (const input of ['h\rttps:example.com/collect', 'ht\rtp:example.com/collect']) {23 // eslint-disable-next-line no-await-in-loop24 await t.throwsAsync(ky(input, {baseUrl: 'https://trusted.test/api/', fetch, retry: 0}), {25 instanceOf: TypeError,26 message: '`input` url protocol must be followed by `//` when using `baseUrl`',27 }, `input: ${JSON.stringify(input)}`);28 }2930 t.is(requests.length, 0);31});3233// The check only guards `baseUrl` resolution. Without a `baseUrl`, the input goes to the `Request` constructor, which parses a slashless special scheme as an absolute URL.34test('a slashless HTTP URL is allowed without baseUrl', async t => {35 const {fetch, requests} = createRecordingFetch();3637 await ky('https:example.com/users', {fetch, retry: 0});3839 t.is(requests[0]!.url, 'https://example.com/users');40});4142// Only leading C0 control or space characters are stripped, like the URL parser does. A space inside the input stays, so `ht tp:` is not a scheme and the input is a relative path.43test('baseUrl resolves an input with a space before the colon as a relative path', async t => {44 const {fetch, requests} = createRecordingFetch();4546 await ky('ht tp:example.com/collect', {baseUrl: 'https://trusted.test/api/', fetch, retry: 0});4748 t.is(requests[0]!.url, 'https://trusted.test/api/ht%20tp:example.com/collect');49});5051// An absolute input bypasses `baseUrl` completely, so a `baseUrl` that cannot be resolved in Node.js is never used. Each case reaches a different part of the absolute input check.52for (const [description, input, expectedUrl] of [53 ['an uppercase scheme', 'HTTPS://example.com/users', 'https://example.com/users'],54 ['a scheme with a digit, plus, dot and hyphen', 'web+x-app.v2://example.com/users', 'web+x-app.v2://example.com/users'],55 ['leading whitespace', ' https://example.com/users', 'https://example.com/users'],56 ['a tab inside the scheme', 'ht\ttps://example.com/users', 'https://example.com/users'],57] as const) {58 test(`an absolute input with ${description} bypasses baseUrl`, async t => {59 const {fetch, requests} = createRecordingFetch();6061 await ky(input, {baseUrl: '/api/', fetch, retry: 0});6263 t.is(requests[0]!.url, expectedUrl);64 });65}6667test('prefix is not applied to a URL input', async t => {68 const {fetch, requests} = createRecordingFetch();6970 await ky(new URL('https://example.com/users'), {prefix: 'https://other.test/api/', fetch, retry: 0});7172 t.is(requests[0]!.url, 'https://example.com/users');73});7475test('prefix is not applied to a Request input', async t => {76 const {fetch, requests} = createRecordingFetch();7778 await ky(new Request('https://example.com/users'), {prefix: 'https://other.test/api/', fetch, retry: 0});7980 t.is(requests[0]!.url, 'https://example.com/users');81});8283// `prefix` is joined to the input before `baseUrl` resolves it, so a slashless scheme in the prefix gets the same check as one in the input.84test('baseUrl rejects a slashless HTTP URL that comes from prefix', async t => {85 const {fetch, requests} = createRecordingFetch();8687 await t.throwsAsync(ky('users', {88 prefix: 'https:evil.test',89 baseUrl: 'https://trusted.test/',90 fetch,91 retry: 0,92 }), {93 instanceOf: TypeError,94 message: '`input` url protocol must be followed by `//` when using `baseUrl`',95 });9697 t.is(requests.length, 0);98});99100test('an absolute prefix makes the input absolute, so baseUrl is ignored', async t => {101 const {fetch, requests} = createRecordingFetch();102103 await ky('users', {104 prefix: 'https://a.test/v1',105 baseUrl: 'https://b.test/root/',106 fetch,107 retry: 0,108 });109110 t.is(requests[0]!.url, 'https://a.test/v1/users');111});112113test('a root-relative prefix resolves against the origin of baseUrl', async t => {114 const {fetch, requests} = createRecordingFetch();115116 await ky('users', {117 prefix: '/v1/',118 baseUrl: 'https://example.com/api/',119 fetch,120 retry: 0,121 });122123 t.is(requests[0]!.url, 'https://example.com/v1/users');124});125126for (const [description, input, expectedUrl] of [127 ['a parent path', '../users', 'https://example.com/users'],128 ['only a query', '?page=2', 'https://example.com/api/items?page=2'],129 ['only a hash', '#top', 'https://example.com/api/items?page=1#top'],130] as const) {131 test(`baseUrl resolves an input with ${description} like the URL parser`, async t => {132 const {fetch, requests} = createRecordingFetch();133134 await ky(input, {baseUrl: 'https://example.com/api/items?page=1', fetch, retry: 0});135136 t.is(requests[0]!.url, expectedUrl);137 });138}139140test('object searchParams add a value to a key that is already in the input URL', async t => {141 const {fetch, requests} = createRecordingFetch();142143 await ky('https://example.com/?tag=a', {searchParams: {tag: 'b'}, fetch, retry: 0});144145 t.deepEqual(new URL(requests[0]!.url).searchParams.getAll('tag'), ['a', 'b']);146});147148// `URLSearchParams#delete()` serializes the whole query again even when the key is missing, which would turn `%20` into `+` and `?flag` into `?flag=`, and rebuild the request with the changed URL.149for (const input of ['https://example.com/?q=a%20b', 'https://example.com/?flag', 'https://example.com/?a=1;b=2']) {150 test(`object searchParams with only an undefined value for a missing key leave ${input} unchanged`, async t => {151 const {fetch, requests} = createRecordingFetch();152153 await ky(input, {searchParams: {missing: undefined}, fetch, retry: 0});154155 t.is(requests[0]!.url, input);156 });157}158159test('object searchParams with an undefined value for a missing key keep the body of a Request input with a non-canonical query', async t => {160 const input = new Request('https://example.com/?q=a%20b', {method: 'POST', body: 'payload'});161162 await ky(input, {163 searchParams: {missing: undefined},164 keepalive: true,165 retry: 0,166 async fetch(request) {167 t.is((request as Request).url, 'https://example.com/?q=a%20b');168 t.is(await (request as Request).text(), 'payload');169 return new Response('ok');170 },171 });172});173174test('object searchParams with an undefined value still remove that key from the input URL', async t => {175 const {fetch, requests} = createRecordingFetch();176177 await ky('https://example.com/?a=1&b=2', {searchParams: {a: undefined}, fetch, retry: 0});178179 t.is(requests[0]!.url, 'https://example.com/?b=2');180});181182test('string searchParams only strip a leading question mark', async t => {183 const {fetch, requests} = createRecordingFetch();184185 await ky('https://example.com/', {searchParams: 'q=why?', fetch, retry: 0});186187 t.is(requests[0]!.url, 'https://example.com/?q=why?');188});189190// An `undefined` value removes its key from the input URL, and every other value is appended after the input query in the order of the object.191test('object searchParams that mix removals and additions keep the order of the input URL and the object', async t => {192 const {fetch, requests} = createRecordingFetch();193194 await ky('https://example.com/?a=1&b=2&c=3', {searchParams: {b: undefined, d: '4', a: '5'}, fetch, retry: 0});195196 t.is(requests[0]!.url, 'https://example.com/?a=1&c=3&d=4&a=5');197});198199test('an undefined value in object searchParams removes every value of that key', async t => {200 const {fetch, requests} = createRecordingFetch();201202 await ky('https://example.com/?a=1&b=2&a=3', {searchParams: {a: undefined}, fetch, retry: 0});203204 t.is(requests[0]!.url, 'https://example.com/?b=2');205});206207test('object searchParams send falsy and non-string values as strings', async t => {208 const {fetch, requests} = createRecordingFetch();209210 await ky('https://example.com/', {211 searchParams: {212 zero: 0,213 no: false,214 yes: true,215 fraction: 1.5,216 },217 fetch,218 retry: 0,219 });220221 t.is(requests[0]!.url, 'https://example.com/?zero=0&no=false&yes=true&fraction=1.5');222});223224test('object searchParams encode reserved characters, so a value cannot add another parameter', async t => {225 const {fetch, requests} = createRecordingFetch();226227 await ky('https://example.com/', {searchParams: {q: 'a b&c=d', 'k y': 'v'}, fetch, retry: 0});228229 t.is(requests[0]!.url, 'https://example.com/?q=a+b%26c%3Dd&k+y=v');230});231232test('searchParams pairs and URLSearchParams keep every value of a repeated key after the input query', async t => {233 const {fetch, requests} = createRecordingFetch();234235 await ky('https://example.com/?x=1', {searchParams: [['a', '1'], ['a', '2'], ['b', '3']], fetch, retry: 0});236 await ky('https://example.com/?a=0', {searchParams: new URLSearchParams([['a', '1'], ['a', '2']]), fetch, retry: 0});237238 t.is(requests[0]!.url, 'https://example.com/?x=1&a=1&a=2&b=3');239 t.is(requests[1]!.url, 'https://example.com/?a=0&a=1&a=2');240});241242test('string searchParams with a leading question mark are joined to the input query with an ampersand', async t => {243 const {fetch, requests} = createRecordingFetch();244245 await ky('https://example.com/?a=1', {searchParams: '?b=2&c', fetch, retry: 0});246247 t.is(requests[0]!.url, 'https://example.com/?a=1&b=2&c');248});249250test('string searchParams are appended without encoding the input query or themselves again', async t => {251 const {fetch, requests} = createRecordingFetch();252253 await ky('https://example.com/?q=a%20b', {searchParams: 'r=c+d&s=e%20f', fetch, retry: 0});254255 t.is(requests[0]!.url, 'https://example.com/?q=a%20b&r=c+d&s=e%20f');256});257258for (const [input, expectedUrl] of [259 ['https://example.com/path#hash', 'https://example.com/path?a=1#hash'],260 ['https://example.com/path?x=1#hash', 'https://example.com/path?x=1&a=1#hash'],261] as const) {262 test(`string searchParams go before the hash of ${input}`, async t => {263 const {fetch, requests} = createRecordingFetch();264265 await ky(input, {searchParams: 'a=1', fetch, retry: 0});266267 t.is(requests[0]!.url, expectedUrl);268 });269}270271for (const [description, searchParameters] of [272 ['an empty string', ''],273 ['a lone question mark', '?'],274 ['an empty object', {}],275 ['an empty URLSearchParams', new URLSearchParams()],276 ['an empty array', []],277] as const) {278 test(`searchParams with ${description} leave a non-canonical input URL unchanged`, async t => {279 const {fetch, requests} = createRecordingFetch();280281 await ky('https://example.com/?q=a%20b', {searchParams: searchParameters, fetch, retry: 0});282283 t.is(requests[0]!.url, 'https://example.com/?q=a%20b');284 });285}286287// `.extend()` stores an `undefined` key as a deletion marker on the merged `URLSearchParams`, which must only touch an input URL that has the key, like an `undefined` value in the request options.288test('a deletion marker from .extend() only rewrites an input URL that has the key', async t => {289 const {fetch, requests} = createRecordingFetch();290 const api = ky.create({searchParams: {a: '1'}}).extend({searchParams: {a: undefined}});291292 await api('https://example.com/?q=a%20b', {fetch, retry: 0});293 await api('https://example.com/?a=0&b=2', {fetch, retry: 0});294295 t.is(requests[0]!.url, 'https://example.com/?q=a%20b');296 t.is(requests[1]!.url, 'https://example.com/?b=2');297});298299// The `Request` input's `content-type` comes from its own body, so it must not describe a replacement `URLSearchParams` body.300test('a URLSearchParams body replaces the content-type of a Request input', async t => {301 const {fetch, requests} = createRecordingFetch();302 const input = new Request('https://example.com/', {method: 'POST', body: 'plain'});303304 await ky(input, {body: new URLSearchParams({a: '1'}), fetch, retry: 0});305306 t.is(requests[0]!.headers.get('content-type'), 'application/x-www-form-urlencoded;charset=UTF-8');307});308309test('a content-type from the headers option is kept for a FormData body on a Request input', async t => {310 const {fetch, requests} = createRecordingFetch();311 const input = new Request('https://example.com/', {method: 'POST', body: 'plain'});312 const body = new FormData();313 body.append('field', 'value');314315 await ky(input, {316 body,317 headers: {'content-type': 'multipart/form-data; boundary=custom'},318 fetch,319 retry: 0,320 });321322 t.is(requests[0]!.headers.get('content-type'), 'multipart/form-data; boundary=custom');323});324

Fix CISindre Sorhusbefore adoptiond9ddb03

line 325why, one step back
325// The `Request` constructor only normalizes the methods the Fetch standard lists. Runtimes from before `QUERY` was added keep a lowercase `query` on a `Request` input, so Ky must uppercase it.

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 326–404why, one step back
326test('a standard method from a Request input is uppercased', async t => {
327 const {fetch, requests} = createRecordingFetch();328 const input = new Request('https://example.com/', {method: 'query'});329330 await ky(input, {fetch, retry: 0});331332 t.is(requests[0]!.method, 'QUERY');333});334335// Option merging rejects an array `context`, but an `init` hook assigns straight onto the options object.336test('an init hook that sets context to an array gets an error naming the option', async t => {337 const {fetch, requests} = createRecordingFetch();338339 await t.throwsAsync(ky('https://example.com', {340 fetch,341 hooks: {342 init: [options => {343 options.context = [] as never;344 }],345 },346 }), {347 instanceOf: TypeError,348 message: 'The `context` option must be an object',349 });350351 t.is(requests.length, 0);352});353354// Standard request options are already applied to the `Request`, so repeating them in the init object would let `fetch()` apply them a second time.355test('fetch does not receive standard request options in its init object', async t => {356 const {fetch, requests, inits} = createRecordingFetch();357358 await ky.post('https://example.com', {359 body: 'body',360 headers: {'x-custom': 'value'},361 mode: 'cors',362 credentials: 'include',363 cache: 'no-store',364 redirect: 'manual',365 referrer: 'about:client',366 referrerPolicy: 'no-referrer',367 integrity: 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=',368 keepalive: false,369 signal: new AbortController().signal,370 window: undefined,371 priority: 'low',372 fetch,373 retry: 0,374 });375376 t.is(requests[0]!.integrity, 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=');377 t.deepEqual(Object.keys(inits[0]!), ['priority']);378});379380test('fetch does not receive Ky options in its init object', async t => {381 const {fetch, inits} = createRecordingFetch();382383 await ky.post('users', {384 json: {a: 1},385 parseJson: JSON.parse,386 stringifyJson: JSON.stringify,387 searchParams: {page: 1},388 baseUrl: 'https://example.com/',389 prefix: 'api',390 retry: 0,391 timeout: 1000,392 totalTimeout: 2000,393 maxResponseSize: 1000,394 hooks: {},395 throwHttpErrors: true,396 onDownloadProgress: () => undefined,397 onUploadProgress: () => undefined,398 context: {token: 'secret'},399 dispatcher: 'agent',400 fetch,401 } as never);402403 t.deepEqual(Object.keys(inits[0]!), ['dispatcher']);404});