Skip to content
Myr

merge.ts

This file

Path

test/merge.ts

389 lines · 12.6 KiB · TypeScript

Last changed by

RefactorSindre Sorhusbefore adoptiona5ed57b

History of this file

Take it

RefactorSindre Sorhusbefore adoptiona5ed57b

lines 1–389why, one step back
1import test from 'ava';
2import ky, {replaceOption, type Hooks} from '../source/index.js';3import {validateAndMerge} from '../source/utils/merge.js';45const echoUrl = async (request: Request) => new Response(request.url);6const echoBody = async (request: Request) => new Response(await request.text());7const echoHeaders = async (request: Request) => new Response(JSON.stringify(Object.fromEntries(request.headers)));89// `cloneDeep`1011test('an `init` hook mutating an object inside a `json` array does not leak into the next request', async t => {12 const bodies: string[] = [];13 const api = ky.create({14 json: {items: [{count: 1}]},15 async fetch(request) {16 bodies.push(await request.text());17 return new Response('ok');18 },19 hooks: {20 init: [21 options => {22 (options.json as {items: Array<{count: number}>}).items[0]!.count++;23 },24 ],25 },26 });2728 await api.post('https://example.com');29 await api.post('https://example.com');3031 t.deepEqual(bodies, ['{"items":[{"count":2}]}', '{"items":[{"count":2}]}']);32});3334test('an own `__proto__` key in `json` survives the `init` hook copy', async t => {35 const json: unknown = JSON.parse('{"__proto__":{"a":1},"b":2}');3637 const body = await ky.post('https://example.com', {38 json,39 fetch: echoBody,40 hooks: {41 init: [() => undefined],42 },43 }).text();4445 t.is(body, '{"__proto__":{"a":1},"b":2}');46});4748test('a nested non-enumerable `json` property is not sent, even when an `init` hook copies the body', async t => {49 const nested: Record<string, unknown> = {visible: 1};50 Object.defineProperty(nested, 'hidden', {value: 2, enumerable: false});5152 for (const init of [[], [() => undefined]]) {53 // eslint-disable-next-line no-await-in-loop54 const body = await ky.post('https://example.com', {55 json: {nested},56 fetch: echoBody,57 hooks: {init},58 }).text();5960 t.is(body, '{"nested":{"visible":1}}');61 }62});6364test('the `init` hook copy of `json` keeps nested symbol-keyed values', async t => {65 const symbol = Symbol('meta');66 let seen: unknown;6768 await ky.post('https://example.com', {69 json: {nested: {[symbol]: 'meta', value: 1}},70 fetch: async () => new Response('ok'),71 hooks: {72 init: [73 options => {74 seen = (options.json as {nested: Record<symbol, unknown>}).nested[symbol];75 },76 ],77 },78 });7980 t.is(seen, 'meta');81});8283// Headers8485test('the string "undefined" in header pairs is sent as a value instead of removing the header', async t => {86 const api = ky.create({headers: {'x-a': '1', 'x-b': '1'}, fetch: echoHeaders});8788 const headers = await api('https://example.com', {89 headers: [['x-a', 'undefined']],90 }).json<Record<string, string>>();9192 t.is(headers['x-a'], 'undefined');93 t.is(headers['x-b'], '1');94});9596test('the string "undefined" in a plain object header is sent as a value instead of removing the header', async t => {97 const api = ky.create({headers: {'x-a': '1'}, fetch: echoHeaders});9899 const headers = await api('https://example.com', {100 headers: {'x-a': 'undefined'},101 }).json<Record<string, string>>();102103 t.is(headers['x-a'], 'undefined');104});105106test('an `init` hook sees a header removed with `undefined` as a lowercase key with an `undefined` value', async t => {107 let initHeaders: Record<string, string | undefined> | undefined;108 const api = ky.create({headers: {'X-Removed': '1', 'X-Kept': '1'}}).extend({headers: {'X-REMOVED': undefined}});109110 const headers = await api('https://example.com', {111 fetch: echoHeaders,112 hooks: {113 init: [114 options => {115 initHeaders = {...options.headers as Record<string, string | undefined>};116 },117 ],118 },119 }).json<Record<string, string>>();120121 t.true(Object.hasOwn(initHeaders!, 'x-removed'));122 t.deepEqual(initHeaders, {'x-removed': undefined, 'x-kept': '1'});123 t.false('x-removed' in headers);124});125126test('repeated header pairs replace an inherited value and keep every repeated value', async t => {127 const api = ky.create({headers: {'x-a': '0'}, fetch: echoHeaders});128129 const headers = await api('https://example.com', {130 headers: [['x-a', '1'], ['x-a', '2']],131 }).json<Record<string, string>>();132133 t.is(headers['x-a'], '1, 2');134});135136test('a plain object header replaces every value of a repeated header in a `Headers` default', async t => {137 const api = ky.create({headers: new Headers([['x-a', '1'], ['x-a', '2']]), fetch: echoHeaders});138139 const replaced = await api('https://example.com', {headers: {'x-a': '3'}}).json<Record<string, string>>();140 const kept = await api('https://example.com', {headers: {'x-b': '3'}}).json<Record<string, string>>();141142 t.is(replaced['x-a'], '3');143 t.is(kept['x-a'], '1, 2');144});145146test('merging does not rewrite nested user data with a `headers` key', async t => {147 const api = ky.create({json: {headers: {'X-Name': 'a'}}, fetch: echoBody}).extend({json: {headers: {'x-other': 'b'}}});148149 t.is(await api.post('https://example.com').text(), '{"headers":{"X-Name":"a","x-other":"b"}}');150});151152// Search parameters153154test('a merged `URLSearchParams` layer removes the keys it deleted from the layers merged before it', t => {155 const merged = validateAndMerge({searchParams: {a: '0'}}, {searchParams: {a: undefined, b: '2'}}).searchParams as URLSearchParams;156 const result = validateAndMerge({searchParams: {a: '1', c: '3'}}, {searchParams: merged}).searchParams as URLSearchParams;157158 t.is(result.toString(), 'c=3&b=2');159});160161test('extending a string `searchParams` default with an `undefined` key removes the key from the default and the input URL', async t => {162 const api = ky.create({searchParams: 'a=1&b=2', fetch: echoUrl}).extend({searchParams: {a: undefined}});163164 t.is(await api('https://example.com/?a=0&z=9').text(), 'https://example.com/?z=9&b=2');165});166167test('`searchParams: undefined` clears inherited search parameters', async t => {168 const api = ky.create({searchParams: {a: '1'}, fetch: echoUrl});169 const extended = api.extend({searchParams: undefined});170171 t.is(await extended('https://example.com/?keep=1').text(), 'https://example.com/?keep=1');172 t.is(await api('https://example.com', {searchParams: undefined}).text(), 'https://example.com/');173 t.is(await extended('https://example.com', {searchParams: {b: '2'}}).text(), 'https://example.com/?b=2');174});175176test('`searchParams: null` over inherited search parameters gets an error naming the option', async t => {177 const api = ky.create({searchParams: {a: '1'}, fetch: echoUrl});178 const expectation = {instanceOf: TypeError, message: 'The `searchParams` option must not be `null`. Use `undefined` to clear it.'};179180 t.throws(() => api.extend({searchParams: null as never}), expectation);181 await t.throwsAsync(api('https://example.com', {searchParams: null as never}).text(), expectation);182});183184test('merging search parameter pairs over defaults rejects an entry that is not a pair', async t => {185 const api = ky.create({searchParams: {a: '1'}, fetch: echoUrl});186187 // A pair that is not an array, and an array that is not a pair.188 for (const searchParameters of [['a=1'], [['a', '1', '2']]]) {189 // eslint-disable-next-line no-await-in-loop190 await t.throwsAsync(api('https://example.com', {searchParams: searchParameters as never}).text(), {191 instanceOf: TypeError,192 message: 'Array search parameters must be provided in [[key, value], ...] format',193 }, `searchParams: ${JSON.stringify(searchParameters)}`);194 }195});196197// `replaceOption`198199test('resolving a nested `replaceOption` does not change the caller\'s options object', t => {200 const marker = replaceOption({ttl: 60});201 const cloudflare = {cacheTtlByStatus: marker};202 const options: Record<string, unknown> = {cf: cloudflare};203204 const merged = validateAndMerge({cf: {cacheTtlByStatus: {old: 1}}}, options) as Record<string, unknown>;205 const unmerged = validateAndMerge(options) as Record<string, unknown>;206207 t.deepEqual(merged.cf, {cacheTtlByStatus: {ttl: 60}});208 t.deepEqual(unmerged.cf, {cacheTtlByStatus: {ttl: 60}});209 t.is(cloudflare.cacheTtlByStatus, marker);210 t.not(unmerged.cf, cloudflare);211});212213test('resolving `replaceOption` inside an array copies only that array and leaves the caller\'s marker in place', t => {214 const marker = replaceOption(2);215 const list = [1, marker, 3];216 const unmarked = [4];217218 const merged = validateAndMerge({list, unmarked}) as Record<string, unknown>;219220 t.deepEqual(merged.list, [1, 2, 3]);221 t.not(merged.list, list);222 t.is(list[1], marker);223 t.is(merged.unmarked, unmarked);224});225226test('`replaceOption` wrappers nested in `context` are not walked, so large context values are left alone', async t => {227 const large = new Proxy({}, {228 ownKeys() {229 throw new Error('The context value was walked');230 },231 });232233 t.is(await ky('https://example.com', {234 context: {large},235 fetch: async () => new Response('ok'),236 }).text(), 'ok');237});238239// Hooks240241test('`replaceOption(undefined)` on a single hook type clears only that hook type', async t => {242 const calls: string[] = [];243 const api = ky.create({244 fetch: async () => new Response('ok'),245 hooks: {246 beforeRequest: [247 () => {248 calls.push('beforeRequest');249 },250 ],251 afterResponse: [252 () => {253 calls.push('afterResponse');254 },255 ],256 },257 }).extend({hooks: {beforeRequest: replaceOption(undefined as Hooks['beforeRequest'])}});258259 await api('https://example.com');260261 t.deepEqual(calls, ['afterResponse']);262});263264test('`beforeRetry` hooks from the instance, an extension and the request run in that order', async t => {265 const calls: string[] = [];266 const hook = (name: string) => () => {267 calls.push(name);268 };269270 let attempts = 0;271 const api = ky.create({272 retry: {limit: 1, delay: () => 0},273 async fetch() {274 attempts++;275 return new Response('', {status: attempts === 1 ? 500 : 200});276 },277 hooks: {beforeRetry: [hook('instance')]},278 }).extend({hooks: {beforeRetry: [hook('extension')]}});279280 await api('https://example.com', {hooks: {beforeRetry: [hook('request')]}});281282 t.deepEqual(calls, ['instance', 'extension', 'request']);283});284285// `context`286287test('merging `context` copies only enumerable properties', async t => {288 const context: Record<string, unknown> = {visible: 1};289 Object.defineProperty(context, 'hidden', {value: 2, enumerable: false});290 let seen: Record<string, unknown> | undefined;291292 await ky.create({context: {base: 0}})('https://example.com', {293 context,294 fetch: async () => new Response('ok'),295 hooks: {296 beforeRequest: [297 ({options}) => {298 seen = options.context;299 },300 ],301 },302 });303304 t.deepEqual(seen, {base: 0, visible: 1});305 t.false('hidden' in seen!);306});307308// `create` and `extend`309310test('mutating an inherited `URLSearchParams` inside an `extend` callback does not change the parent instance', async t => {311 const parent = ky.create({searchParams: new URLSearchParams('a=1'), fetch: echoUrl});312313 parent.extend(options => {314 (options.searchParams as URLSearchParams).append('child', '1');315 return {};316 });317318 t.is(await parent('https://example.com').text(), 'https://example.com/?a=1');319});320321test('the function form of `.extend()` on the root `ky` receives an empty object', t => {322 let received: unknown;323 ky.extend(options => {324 received = options;325 return {};326 });327328 t.deepEqual(received, {});329});330331test('the function form of `.extend()` is called once when extending, not for every request', async t => {332 let calls = 0;333 const api = ky.create({fetch: async () => new Response('ok')}).extend(() => {334 calls++;335 return {};336 });337338 t.is(calls, 1);339 await api('https://example.com');340 await api('https://example.com');341 t.is(calls, 1);342});343344test('`.create()` on an instance does not inherit that instance\'s defaults', async t => {345 const parent = ky.create({headers: {'x-parent': '1'}, searchParams: {parent: '1'}});346 const created = parent.create({fetch: echoHeaders});347348 const headers = await created('https://example.com').json<Record<string, string>>();349 t.false('x-parent' in headers);350 t.is(await created('https://example.com', {fetch: echoUrl}).text(), 'https://example.com/');351});352353test('a method shortcut wins over a `method` in the request options and the defaults', async t => {354 const api = ky.create({method: 'put', fetch: async request => new Response(request.method)});355356 t.is(await api.post('https://example.com', {method: 'patch'}).text(), 'POST');357 t.is(await api.delete('https://example.com').text(), 'DELETE');358 t.is(await api('https://example.com', {method: 'patch'}).text(), 'PATCH');359 t.is(await api('https://example.com').text(), 'PUT');360});361362test('the function form of `.extend()` appends hooks after the parent hooks', async t => {363 const calls: string[] = [];364 const parent = ky.create({365 fetch: async () => new Response('ok'),366 hooks: {367 beforeRequest: [368 () => {369 calls.push('parent');370 },371 ],372 },373 });374375 const child = parent.extend(() => ({376 hooks: {377 beforeRequest: [378 () => {379 calls.push('child');380 },381 ],382 },383 }));384385 await child('https://example.com');386 await parent('https://example.com');387388 t.deepEqual(calls, ['parent', 'child', 'parent']);389});