context.ts
This file
Path
test/context.ts
403 lines · 9.9 KiB · TypeScript
Last changed by
Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5
History of this fileTake it
1import test from 'ava';2import ky, {isHTTPError} from '../source/index.js';3import {createHttpTestServer} from './helpers/create-http-test-server.js';45test('context is available in all hooks', async t => {6 t.plan(4);78 const server = await createHttpTestServer(t);9 let requestCount = 0;10 server.get('/', (_request, response) => {11 requestCount++;12 if (requestCount === 1) {13 response.sendStatus(500);14 } else {15 response.json({success: true});16 }17 });1819 const context = {id: '123'};2021 await t.throwsAsync(22 ky.get(server.url, {23 context,24 retry: {limit: 0},25 hooks: {26 beforeRequest: [27 ({options}) => {28 t.deepEqual(options.context, context);29 },30 ],31 afterResponse: [32 async ({options}) => {33 t.deepEqual(options.context, context);34 },35 ],36 beforeError: [37 ({error}) => {38 if (isHTTPError(error)) {39 t.deepEqual(error.options.context, context);40 }4142 return error;43 },44 ],45 },46 }).json(),47 );4849 // Test beforeRetry hook50 await ky.get(server.url, {51 context,52 retry: {limit: 1},53 hooks: {54 beforeRetry: [55 async ({options}) => {56 t.deepEqual(options.context, context);57 },58 ],59 },60 }).json();61});6263test('context works with ky.create and ky.extend', async t => {64 const server = await createHttpTestServer(t);65 server.get('/', (_request, response) => {66 response.json({success: true});67 });6869 const baseApi = ky.create({70 baseUrl: server.url,71 context: {base: 'value'},72 });7374 await baseApi.get('', {75 hooks: {76 beforeRequest: [77 ({options}) => {78 t.deepEqual(options.context, {base: 'value'});79 },80 ],81 },82 }).json();8384 const extendedApi = baseApi.extend({context: {extended: 'value'}});85 await extendedApi.get('', {86 context: {request: 'value'},87 hooks: {88 beforeRequest: [89 ({options}) => {90 t.deepEqual(options.context, {base: 'value', extended: 'value', request: 'value'});91 },92 ],93 },94 }).json();95});9697test('context is preserved across retries', async t => {98 const server = await createHttpTestServer(t);99 let requestCount = 0;100 server.get('/', (_request, response) => {101 requestCount++;102 if (requestCount <= 2) {103 response.sendStatus(500);104 } else {105 response.json({success: true});106 }107 });108109 const context = {id: 'session'};110 let beforeRequestCallCount = 0;111 let beforeRetryCallCount = 0;112113 await ky.get(server.url, {114 context,115 retry: {limit: 2},116 hooks: {117 beforeRequest: [118 ({options}) => {119 t.deepEqual(options.context, context);120 beforeRequestCallCount++;121 },122 ],123 beforeRetry: [124 ({options}) => {125 t.deepEqual(options.context, context);126 beforeRetryCallCount++;127 },128 ],129 },130 }).json();131132 t.is(beforeRequestCallCount, 1);133 t.is(beforeRetryCallCount, 2);134});135136test('context defaults to empty object when not provided', async t => {137 const server = await createHttpTestServer(t);138 server.get('/', (_request, response) => {139 response.json({success: true});140 });141142 await ky.get(server.url, {143 hooks: {144 beforeRequest: [({options}) => t.deepEqual(options.context, {})],145 },146 }).json();147});148149test('context defaults to empty object in init hooks', async t => {150 const seenContexts: unknown[] = [];151 const options = {152 fetch: async () => new Response('ok'),153 };154155 await ky('https://example.com', {156 ...options,157 hooks: {158 init: [159 options => {160 seenContexts.push(options.context);161 // The readme promises an object, so hooks can add to it without checks.162 options.context!['fromInit'] = true;163 },164 ],165 beforeRequest: [166 ({options}) => {167 seenContexts.push(options.context);168 },169 ],170 },171 });172173 t.deepEqual(seenContexts, [{fromInit: true}, {fromInit: true}]);174175 // Also when the init hook comes from an extended instance and the request passes no context.176 seenContexts.length = 0;177 await ky.extend({178 hooks: {179 init: [180 options => {181 seenContexts.push(options.context);182 },183 ],184 },185 })('https://example.com', options);186 t.deepEqual(seenContexts, [{}]);187188 // A provided context is passed through unchanged.189 seenContexts.length = 0;190 await ky('https://example.com', {191 ...options,192 context: {id: 1},193 hooks: {194 init: [195 options => {196 seenContexts.push(options.context);197 },198 ],199 },200 });201 t.deepEqual(seenContexts, [{id: 1}]);202});203204test('context is shallow merged', async t => {205 const server = await createHttpTestServer(t);206 server.get('/', (_request, response) => {207 response.json({success: true});208 });209210 const baseApi = ky.create({211 baseUrl: server.url,212 context: {213 auth: {apiKey: 'base', userId: 'user-123'},214 settings: {timeout: 5000},215 },216 });217218 const extendedApi = baseApi.extend({219 context: {220 auth: {apiKey: 'extended'},221 settings: {retries: 3},222 newField: 'added',223 },224 });225226 await extendedApi.get('', {227 hooks: {228 beforeRequest: [229 ({options}) => {230 const context = options.context as any;231 t.is(context.auth.apiKey, 'extended');232 t.is(context.auth.userId, undefined);233 t.is(context.settings.timeout, undefined);234 t.is(context.settings.retries, 3);235 t.is(context.newField, 'added');236 },237 ],238 },239 }).json();240});241242for (const withInitHook of [false, true]) {243 test(`context preserves symbol-keyed metadata with init hook ${withInitHook}`, async t => {244 const metadataKey = Symbol('metadata');245 const context = {label: 'request', [metadataKey]: {traceId: 'trace-123'}};246 let beforeRequestCalls = 0;247 let initCalls = 0;248 const response = await ky('https://example.com', {249 context,250 hooks: {251 init: withInitHook252 ? [options => {253 initCalls++;254 t.deepEqual(options.context, context);255 }]256 : [],257 beforeRequest: [({options}) => {258 beforeRequestCalls++;259 t.deepEqual(options.context, context);260 }],261 },262 fetch: async () => new Response('ok'),263 }).text();264265 t.is(response, 'ok');266 t.is(initCalls, withInitHook ? 1 : 0);267 t.is(beforeRequestCalls, 1);268 });269}270271// The `init` hook copy is shallow, so it must still copy symbol keys, and replacing one only affects the current request.272test('init hook symbol-keyed context assignments stay isolated between requests', async t => {273 const metadataKey = Symbol('metadata');274 const metadata = {attempt: 0};275 const context = {[metadataKey]: metadata};276 let initCalls = 0;277 let beforeRequestCalls = 0;278 const api = ky.create({279 context,280 hooks: {281 init: [options => {282 initCalls++;283 t.is(Reflect.get(options.context, metadataKey), metadata);284 Reflect.set(options.context, metadataKey, {attempt: 1});285 }],286 beforeRequest: [({options}) => {287 beforeRequestCalls++;288 t.deepEqual(options.context, {[metadataKey]: {attempt: 1}});289 }],290 },291 fetch: async () => new Response('ok'),292 });293294 t.is(await api('https://example.com').text(), 'ok');295 t.is(await api('https://example.com').text(), 'ok');296 t.deepEqual(metadata, {attempt: 0});297 t.is(initCalls, 2);298 t.is(beforeRequestCalls, 2);299});300301// Context is merged shallowly, so a nested object is shared by every request from the instance, which lets hooks keep state such as a cache in it. An `init` hook gets a shallow copy too, so having one does not change this.302test('a nested context object is shared across requests', async t => {303 const context = {cache: {count: 0}};304 const api = ky.create({305 context,306 hooks: {307 init: [() => undefined],308 beforeRequest: [({options}) => {309 (options.context.cache as typeof context.cache).count++;310 }],311 },312 fetch: async () => new Response('ok'),313 });314315 await api('https://example.com/1').text();316 await api('https://example.com/2').text();317318 t.is(context.cache.count, 2);319});320321test('hooks in one request still share a single context object', async t => {322 const seen: unknown[] = [];323 const api = ky.create({324 retry: {limit: 0},325 hooks: {326 beforeRequest: [327 ({options}) => {328 options.context.shared = 'set-in-beforeRequest';329 seen.push(options.context);330 },331 // Replacing the request resets the normalized options cache, so the shared context must survive it.332 ({request}) => new Request(request),333 ],334 afterResponse: [({options}) => {335 seen.push(options.context);336 }],337 },338 fetch: async () => new Response('ok'),339 });340341 await api('https://example.com').text();342343 t.is(seen.length, 2);344 t.is(seen[0], seen[1]);345 t.deepEqual(seen[1], {shared: 'set-in-beforeRequest'});346});347348// `init` hooks get a deep copy of `json`, which must keep a null prototype.349test('a nested null-prototype json value keeps its prototype in an `init` hook', async t => {350 const bag = Object.create(null) as Record<string, unknown>;351 bag.count = 1;352353 let seen: Record<string, unknown> | undefined;354 const api = ky.create({355 json: {bag},356 hooks: {357 init: [options => {358 seen = (options.json as {bag: Record<string, unknown>}).bag;359 }],360 },361 fetch: async () => new Response('ok'),362 });363364 await api.post('https://example.com').text();365366 t.is(Object.getPrototypeOf(seen!), null);367 // A null-prototype object has no inherited members.368 t.is(seen!.toString, undefined);369 t.is(seen!.count, 1);370 // The clone is a copy, so mutating it does not touch the caller's object.371 seen!['count'] = 99;372 t.is(bag.count, 1);373});374375// `extend(fn)` is documented as passing a copy so mutations inside the callback cannot leak into the parent instance's defaults. The copy was shallow, so a nested value still pointed at the parent's object.376test('mutating nested context inside an `extend` callback does not change the parent instance', async t => {377 const contexts: Array<Record<string, unknown>> = [];378 const record = async (instance: typeof parent) => {379 await instance('https://example.com', {380 fetch: async () => new Response('ok'),381 hooks: {382 beforeRequest: [({options}) => {383 contexts.push(options.context);384 }],385 },386 }).text();387 };388389 const parent = ky.create({context: {session: {token: 'parent'}, top: 'parent'}});390 await record(parent);391392 parent.extend((options: any) => {393 options.context.session.token = 'child';394 return {};395 });396397 await record(parent);398399 t.deepEqual(contexts, [400 {session: {token: 'parent'}, top: 'parent'},401 {session: {token: 'parent'}, top: 'parent'},402 ]);403});