Skip to content
Myr

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 file

Take it

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

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

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

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

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 3–7why, one step back
3import {createHttpTestServer} from './helpers/create-http-test-server.js';
45test('context is available in all hooks', async t => {6 t.plan(4);7

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 8why, one step back
8 const server = await createHttpTestServer(t);

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 9–26why, one step back
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: [

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 27why, one step back
27 ({options}) => {

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 28–31why, one step back
28 t.deepEqual(options.context, context);
29 },30 ],31 afterResponse: [

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 32why, one step back
32 async ({options}) => {

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 33–36why, one step back
33 t.deepEqual(options.context, context);
34 },35 ],36 beforeError: [

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 37why, one step back
37 ({error}) => {

Make `beforeError` hook receive all errors (#829)Sindre Sorhusbefore adoption101c74b

lines 38–41why, one step back
38 if (isHTTPError(error)) {
39 t.deepEqual(error.options.context, context);40 }41

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 42–63why, one step back
42 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 => {

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 64why, one step back
64 const server = await createHttpTestServer(t);

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 65–69why, one step back
65 server.get('/', (_request, response) => {
66 response.json({success: true});67 });6869 const baseApi = ky.create({

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

line 70why, one step back
70 baseUrl: server.url,

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 71–76why, one step back
71 context: {base: 'value'},
72 });7374 await baseApi.get('', {75 hooks: {76 beforeRequest: [

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 77why, one step back
77 ({options}) => {

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 78–88why, one step back
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: [

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 89why, one step back
89 ({options}) => {

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 90–97why, one step back
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 => {

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 98why, one step back
98 const server = await createHttpTestServer(t);

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 99–109why, one step back
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'};

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 110–111why, one step back
110 let beforeRequestCallCount = 0;
111 let beforeRetryCallCount = 0;

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 112–117why, one step back
112
113 await ky.get(server.url, {114 context,115 retry: {limit: 2},116 hooks: {117 beforeRequest: [

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 118why, one step back
118 ({options}) => {

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

line 119why, one step back
119 t.deepEqual(options.context, context);

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

line 120why, one step back
120 beforeRequestCallCount++;

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 121–122why, one step back
121 },
122 ],

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 123–128why, one step back
123 beforeRetry: [
124 ({options}) => {125 t.deepEqual(options.context, context);126 beforeRetryCallCount++;127 },128 ],

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 129–131why, one step back
129 },
130 }).json();131

Treat hook errors as fatal outside retry handling (#834)Sindre Sorhusbefore adoption90c6d00

lines 132–133why, one step back
132 t.is(beforeRequestCallCount, 1);
133 t.is(beforeRetryCallCount, 2);

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 134–136why, one step back
134});
135136test('context defaults to empty object when not provided', async t => {

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 137why, one step back
137 const server = await createHttpTestServer(t);

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 138–143why, one step back
138 server.get('/', (_request, response) => {
139 response.json({success: true});140 });141142 await ky.get(server.url, {143 hooks: {

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 144why, one step back
144 beforeRequest: [({options}) => t.deepEqual(options.context, {})],

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 145–148why, one step back
145 },
146 }).json();147});148

Fix `context` being `undefined` in `init` hooksSindre Sorhusbefore adoptionfa9f6a7

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

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

line 204why, one step back
204test('context is shallow merged', async t => {

Simplify testsSindre Sorhusbefore adoptiondfa3f59

line 205why, one step back
205 const server = await createHttpTestServer(t);

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 206–210why, one step back
206 server.get('/', (_request, response) => {
207 response.json({success: true});208 });209210 const baseApi = ky.create({

Add `baseUrl` option, rename `prefixUrl` to `prefix`, and allow leading slashes in input (#606)Seth Holladaybefore adoption1f2ad7f

line 211why, one step back
211 baseUrl: server.url,

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

lines 212–228why, one step back
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: [

Unify hook signatures around a single state object (#827)Sindre Sorhusbefore adoptionecdd45e

line 229why, one step back
229 ({options}) => {

Add `context` option (#772)Sindre Sorhusbefore adoption1e749ba

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

Preserve symbol-keyed context in init hooksSindre Sorhusbefore adoptiona8753dc

lines 241–270why, one step back
241
242for (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}270

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

lines 271–272why, one step back
271// 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 => {

Preserve symbol-keyed context in init hooksSindre Sorhusbefore adoptiona8753dc

lines 273–282why, one step back
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++;

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

lines 283–284why, one step back
283 t.is(Reflect.get(options.context, metadataKey), metadata);
284 Reflect.set(options.context, metadataKey, {attempt: 1});

Preserve symbol-keyed context in init hooksSindre Sorhusbefore adoptiona8753dc

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

HardenSindre Sorhusbefore adoption8d8e7a4

line 300why, one step back
300

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

line 301why, one step back
301// 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.

TweaksSindre Sorhusbefore adoption3ded2aa

lines 302–303why, one step back
302test('a nested context object is shared across requests', async t => {
303 const context = {cache: {count: 0}};

HardenSindre Sorhusbefore adoption8d8e7a4

lines 304–306why, one step back
304 const api = ky.create({
305 context,306 hooks: {

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

line 307why, one step back
307 init: [() => undefined],

HardenSindre Sorhusbefore adoption8d8e7a4

line 308why, one step back
308 beforeRequest: [({options}) => {

TweaksSindre Sorhusbefore adoption3ded2aa

line 309why, one step back
309 (options.context.cache as typeof context.cache).count++;

HardenSindre Sorhusbefore adoption8d8e7a4

lines 310–317why, one step back
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();317

TweaksSindre Sorhusbefore adoption3ded2aa

line 318why, one step back
318 t.is(context.cache.count, 2);

HardenSindre Sorhusbefore adoption8d8e7a4

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

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

lines 348–349why, one step back
348// `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 => {

HardenSindre Sorhusbefore adoption8d8e7a4

lines 350–354why, one step back
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({

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

line 355why, one step back
355 json: {bag},

HardenSindre Sorhusbefore adoption8d8e7a4

line 356why, one step back
356 hooks: {

TweaksSindre Sorhusbefore adoption3ded2aa

line 357why, one step back
357 init: [options => {

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

line 358why, one step back
358 seen = (options.json as {bag: Record<string, unknown>}).bag;

HardenSindre Sorhusbefore adoption8d8e7a4

lines 359–363why, one step back
359 }],
360 },361 fetch: async () => new Response('ok'),362 });363

Stop surfacing progress callback errorsSindre Sorhusbefore adoption13c8da5

line 364why, one step back
364 await api.post('https://example.com').text();

HardenSindre Sorhusbefore adoption8d8e7a4

lines 365–373why, one step back
365
366 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});

Explain a missing response and give `extend(fn)` a deep copy of the parent defaultsSindre Sorhusbefore adoption5b7080a

lines 374–403why, one step back
374
375// `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});