forked from sindresorhus/ky
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
2328 lines (1872 loc) · 58.3 KB
/
Copy pathmain.ts
File metadata and controls
2328 lines (1872 loc) · 58.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {Buffer} from 'node:buffer';
import {setTimeout as delay} from 'node:timers/promises';
import test from 'ava';
import {expectTypeOf} from 'expect-type';
import ky, {
HTTPError,
KyError,
SchemaValidationError,
TimeoutError,
isKyError,
replaceOption,
type StandardSchemaV1,
} from '../source/index.js';
import {createHttpTestServer} from './helpers/create-http-test-server.js';
import {parseRawBody} from './helpers/parse-body.js';
const fixture = 'fixture';
type TestSchemaResult<Output> = {value: Output} | {issues: Array<{message: string}>};
const createSchema = <Output>(
validate: (value: unknown) => TestSchemaResult<Output> | Promise<TestSchemaResult<Output>>,
): StandardSchemaV1<unknown, Output> => ({
'~standard': {
version: 1,
vendor: 'test',
validate,
},
});
const isObjectWithValue = (value: unknown): value is {value: unknown} => (
typeof value === 'object'
&& value !== null
&& 'value' in value
);
const createSchemaCallTracker = () => {
let isSchemaCalled = false;
return {
schema: createSchema(() => {
isSchemaCalled = true;
return {value: {value: 1}};
}),
isSchemaCalled: () => isSchemaCalled,
};
};
test('ky()', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.end();
});
const {ok} = await ky(server.url);
t.true(ok);
});
test('GET request', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.method);
});
t.is(await ky(server.url).text(), 'GET');
});
test('POST request', async t => {
const server = await createHttpTestServer(t);
server.post('/', (request, response) => {
response.end(request.method);
});
t.is(await ky.post(server.url).text(), 'POST');
});
test('PUT request', async t => {
const server = await createHttpTestServer(t);
server.put('/', (request, response) => {
response.end(request.method);
});
t.is(await ky.put(server.url).text(), 'PUT');
});
test('PATCH request', async t => {
const server = await createHttpTestServer(t);
server.patch('/', (request, response) => {
response.end(request.method);
});
t.is(await ky.patch(server.url).text(), 'PATCH');
});
test('HEAD request', async t => {
t.plan(2);
const server = await createHttpTestServer(t);
server.head('/', (request, response) => {
response.end(request.method);
t.pass();
});
t.is(await ky.head(server.url).text(), '');
});
test('DELETE request', async t => {
const server = await createHttpTestServer(t);
server.delete('/', (request, response) => {
response.end(request.method);
});
t.is(await ky.delete(server.url).text(), 'DELETE');
});
test('POST JSON', async t => {
t.plan(2);
const server = await createHttpTestServer(t);
server.post('/', async (request, response) => {
t.is(request.headers['content-type'], 'application/json');
response.json(request.body);
});
const json = {
foo: true,
};
const responseJson = await ky.post(server.url, {json}).json();
t.deepEqual(responseJson, json);
});
test('cannot use `body` option with GET or HEAD method', t => {
t.throws(
() => {
void ky.get('https://example.com', {body: 'foobar'});
},
{
message: 'Request with GET/HEAD method cannot have body.',
},
);
t.throws(
() => {
void ky.head('https://example.com', {body: 'foobar'});
},
{
message: 'Request with GET/HEAD method cannot have body.',
},
);
});
test('cannot use `json` option with GET or HEAD method', t => {
t.throws(
() => {
void ky.get('https://example.com', {json: {}});
},
{
message: 'Request with GET/HEAD method cannot have body.',
},
);
t.throws(
() => {
void ky.head('https://example.com', {json: {}});
},
{
message: 'Request with GET/HEAD method cannot have body.',
},
);
});
test('`json` option overrides the `body` option', async t => {
t.plan(2);
const server = await createHttpTestServer(t);
server.post('/', async (request, response) => {
t.is(request.headers['content-type'], 'application/json');
response.json(request.body);
});
const json = {
foo: 'bar',
};
const responseJson = await ky
.post(server.url, {
body: 'hello',
json,
})
.json();
t.deepEqual(responseJson, json);
});
test('custom headers', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.headers.unicorn);
});
t.is(
await ky(server.url, {
headers: {
unicorn: fixture,
},
}).text(),
fixture,
);
});
test('JSON with custom Headers instance', async t => {
t.plan(3);
const server = await createHttpTestServer(t);
server.post('/', async (request, response) => {
t.is(request.headers.unicorn, 'rainbow');
t.is(request.headers['content-type'], 'application/json');
response.json(request.body);
});
const json = {
foo: true,
};
const responseJson = await ky
.post(server.url, {
headers: new Headers({unicorn: 'rainbow'}),
json,
})
.json();
t.deepEqual(responseJson, json);
});
test('.json() with custom accept header', async t => {
t.plan(2);
const server = await createHttpTestServer(t);
server.get('/', async (request, response) => {
t.is(request.headers.accept, 'foo/bar');
response.json({});
});
const responseJson = await ky(server.url, {
headers: {accept: 'foo/bar'},
}).json();
t.deepEqual(responseJson, {});
});
test('.json() when response is chunked', async t => {
const server = await createHttpTestServer(t);
server.get('/', async (request, response) => {
response.write('[');
response.write('"one",');
response.write('"two"');
response.end(']');
});
const responseJson = await ky.get<['one', 'two']>(server.url).json();
expectTypeOf(responseJson).toEqualTypeOf<['one', 'two'] | undefined>();
t.deepEqual(responseJson, ['one', 'two']);
});
test('.json() with invalid JSON body', async t => {
const server = await createHttpTestServer(t);
server.get('/', async (request, response) => {
t.is(request.headers.accept, 'application/json');
response.end('not json');
});
await t.throwsAsync(ky.get(server.url).json(), {
message: /Unexpected token/,
});
});
test('.json() with empty body', async t => {
t.plan(2);
const server = await createHttpTestServer(t);
server.get('/', async (request, response) => {
t.is(request.headers.accept, 'application/json');
response.end();
});
const responseJson = await ky.get<{foo: string}>(server.url).json();
expectTypeOf(responseJson).toEqualTypeOf<{foo: string} | undefined>();
t.is(responseJson, undefined);
});
test('.json() with 204 response and empty body', async t => {
t.plan(2);
const server = await createHttpTestServer(t);
server.get('/', async (request, response) => {
t.is(request.headers.accept, 'application/json');
response.status(204).end();
});
const responseJson = await ky(server.url).json();
t.is(responseJson, undefined);
});
test('.json() with 204 response does not call parseJson', async t => {
const server = await createHttpTestServer(t);
server.get('/', async (_request, response) => {
response.status(204).end();
});
let parseJsonCalled = false;
const result = await ky(server.url, {
parseJson(text) {
parseJsonCalled = true;
return JSON.parse(text);
},
}).json();
t.is(result, undefined);
t.false(parseJsonCalled);
});
test('.json() with empty body does not call parseJson', async t => {
const server = await createHttpTestServer(t);
server.get('/', async (_request, response) => {
response.end();
});
let parseJsonCalled = false;
const result = await ky(server.url, {
parseJson(text) {
parseJsonCalled = true;
return JSON.parse(text);
},
}).json();
t.is(result, undefined);
t.false(parseJsonCalled);
});
test('.json(schema) returns validated output and infers type', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.json({value: 1});
});
const schema = createSchema<{value: number}>(value => {
if (
isObjectWithValue(value)
&& typeof value.value === 'number'
) {
return {value: {value: value.value}};
}
return {issues: [{message: 'Expected {value:number}'}]};
});
const responseJson = await ky.get(server.url).json(schema);
expectTypeOf(responseJson).toEqualTypeOf<{value: number}>();
t.deepEqual(responseJson, {value: 1});
});
test('.json(schema) accepts schema with typed input generic', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.json('1');
});
const schema: StandardSchemaV1<string, number> = {
'~standard': {
version: 1,
vendor: 'test',
validate(value) {
if (typeof value === 'string') {
return {value: Number(value)};
}
return {issues: [{message: 'Expected string'}]};
},
},
};
const responseJson = await ky.get(server.url).json(schema);
expectTypeOf(responseJson).toEqualTypeOf<number>();
t.is(responseJson, 1);
});
test('.json(schema) accepts callable schema objects', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.json({value: 1});
});
const schema: StandardSchemaV1<unknown, {value: number}> = Object.assign(
() => undefined,
{
'~standard': {
version: 1 as const,
vendor: 'test',
validate(value: unknown) {
if (
isObjectWithValue(value)
&& typeof value.value === 'number'
) {
return {value: {value: value.value}};
}
return {issues: [{message: 'Expected {value:number}'}]};
},
},
},
);
const responseJson = await ky.get(server.url).json(schema);
t.deepEqual(responseJson, {value: 1});
});
test('.json(schema) throws SchemaValidationError when validation fails', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.json({value: 'invalid'});
});
const issues = [{message: 'Expected {value:number}'}];
const schema = createSchema<{value: number}>(() => ({issues}));
const error = await t.throwsAsync(ky.get(server.url).json(schema), {
instanceOf: SchemaValidationError,
message: 'Response schema validation failed',
});
t.false(isKyError(error));
t.deepEqual(error?.issues, issues);
});
test('.json(schema) throws TypeError for invalid schema objects', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.json({value: 1});
});
const invalidSchema = {'~standard': {}} as unknown as StandardSchemaV1;
await t.throwsAsync(ky.get(server.url).json(invalidSchema), {
instanceOf: TypeError,
message: 'The `schema` argument must follow the Standard Schema specification',
});
});
test('.json(schema) throws TypeError for null schema values', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.json({value: 1});
});
const invalidSchema = null as unknown as StandardSchemaV1;
await t.throwsAsync(ky.get(server.url).json(invalidSchema), {
instanceOf: TypeError,
message: 'The `schema` argument must follow the Standard Schema specification',
});
});
test('isKyError works for branded cross-realm KyError subclasses', t => {
class CustomKyError extends KyError {
override name = 'CustomKyError';
}
const error = Object.assign(new Error('cross-realm error'), {
name: 'CustomKyError',
isKyError: new CustomKyError().isKyError,
});
t.true(isKyError(error));
});
test('isKyError does not match unrelated errors named KyError', t => {
const error = new Error('not from ky');
error.name = 'KyError';
t.false(isKyError(error));
});
test('.json(schema) allows schema output transformations', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.json({value: '1'});
});
const schema = createSchema<{value: number}>(value => {
if (
isObjectWithValue(value)
&& typeof value.value === 'string'
) {
return {value: {value: Number(value.value)}};
}
return {issues: [{message: 'Expected {value:string}'}]};
});
const responseJson = await ky.get(server.url).json(schema);
t.deepEqual(responseJson, {value: 1});
});
test('.json(schema) supports async validation', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.json({value: 1});
});
const schema = createSchema<{value: number}>(async value => {
await delay(1);
if (
isObjectWithValue(value)
&& typeof value.value === 'number'
) {
return {value: {value: value.value}};
}
return {issues: [{message: 'Expected {value:number}'}]};
});
const responseJson = await ky.get(server.url).json(schema);
t.deepEqual(responseJson, {value: 1});
});
test('.json(schema) validates empty body values as undefined', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.end();
});
const issues = [{message: 'Expected non-empty JSON'}];
let validatedValue: unknown = Symbol('unset');
const schema = createSchema<unknown>(value => {
validatedValue = value;
return {issues};
});
const error = await t.throwsAsync(ky.get(server.url).json(schema), {
instanceOf: SchemaValidationError,
message: 'Response schema validation failed',
});
t.is(validatedValue, undefined);
t.deepEqual(error?.issues, issues);
});
test('.json(schema) validates 204 responses as undefined', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.status(204).end();
});
const issues = [{message: 'Expected non-empty JSON'}];
let validatedValue: unknown = Symbol('unset');
const schema = createSchema<unknown>(value => {
validatedValue = value;
return {issues};
});
const error = await t.throwsAsync(ky.get(server.url).json(schema), {
instanceOf: SchemaValidationError,
message: 'Response schema validation failed',
});
t.is(validatedValue, undefined);
t.deepEqual(error?.issues, issues);
});
test('.json(schema) with invalid JSON body throws parse error before validation', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.end('not json');
});
const {schema, isSchemaCalled} = createSchemaCallTracker();
await t.throwsAsync(ky.get(server.url).json(schema), {
message: /Unexpected token/,
});
t.false(isSchemaCalled());
});
test('.json(schema) does not run validation for HTTP errors', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.status(500).json({value: 1});
});
const {schema, isSchemaCalled} = createSchemaCallTracker();
await t.throwsAsync(ky.get(server.url).json(schema), {
instanceOf: HTTPError,
});
t.false(isSchemaCalled());
});
test('.json(schema) accepts empty body when schema validates it', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.end();
});
const schema = createSchema<string>(value => ({
value: value === undefined ? 'empty:undefined' : 'non-empty',
}));
const responseJson = await ky.get(server.url).json(schema);
t.is(responseJson, 'empty:undefined');
});
test('.json(schema) runs validation when throwHttpErrors is false', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.status(500).json({error: 'server error'});
});
const schema = createSchema<{error: string}>(value => {
if (
typeof value === 'object'
&& value !== null
&& 'error' in value
) {
return {value: value as {error: string}};
}
return {issues: [{message: 'Expected {error:string}'}]};
});
const responseJson = await ky.get(server.url, {throwHttpErrors: false}).json(schema);
t.deepEqual(responseJson, {error: 'server error'});
});
test('.json(schema) propagates errors thrown by validate()', async t => {
const server = await createHttpTestServer(t);
server.get('/', (_request, response) => {
response.json({value: 1});
});
const schema = createSchema<unknown>(() => {
throw new Error('validate exploded');
});
await t.throwsAsync(ky.get(server.url).json(schema), {
message: 'validate exploded',
});
});
test('timeout option', async t => {
t.plan(2);
let requestCount = 0;
const server = await createHttpTestServer(t);
server.get('/', async (_request, response) => {
requestCount++;
await delay(2000);
response.end(fixture);
});
await t.throwsAsync(ky(server.url, {timeout: 1000}).text(), {
instanceOf: TimeoutError,
});
t.is(requestCount, 1);
});
test('timeout:false option', async t => {
let requestCount = 0;
const server = await createHttpTestServer(t);
server.get('/', async (_request, response) => {
requestCount++;
await delay(1000);
response.end(fixture);
});
await t.notThrowsAsync(ky(server.url, {timeout: false}).text());
t.is(requestCount, 1);
});
test('invalid timeout option', async t => {
// #117
let requestCount = 0;
const server = await createHttpTestServer(t);
server.get('/', async (_request, response) => {
requestCount++;
await delay(1000);
response.end(fixture);
});
await t.throwsAsync(ky(server.url, {timeout: 21_474_836_470}).text(), {
instanceOf: RangeError,
message: 'The `timeout` option cannot be greater than 2147483647',
});
t.is(requestCount, 0);
});
test('timeout option is cancelled when the promise is resolved', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.method);
});
const start = Date.now();
await ky(server.url, {timeout: 2000});
const duration = start - Date.now();
t.true(duration < 10);
});
test('searchParams option', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url.slice(1));
});
const arrayParameters = [
['cats', 'meow'],
['dogs', 'true'],
['opossums', 'false'],
];
const objectParameters = {
cats: 'meow',
dogs: 'true',
opossums: 'false',
};
const searchParameters = new URLSearchParams(arrayParameters);
const stringParameters = '?cats=meow&dogs=true&opossums=false';
const customStringParameters = '?cats&dogs[0]=true&dogs[1]=false';
t.is(await ky(server.url, {searchParams: arrayParameters}).text(), stringParameters);
t.is(await ky(server.url, {searchParams: objectParameters}).text(), stringParameters);
t.is(await ky(server.url, {searchParams: searchParameters}).text(), stringParameters);
t.is(await ky(server.url, {searchParams: stringParameters}).text(), stringParameters);
t.is(await ky(server.url, {searchParams: customStringParameters}).text(), customStringParameters);
});
test('searchParams option with undefined values', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url.slice(1));
});
const objectWithUndefined = {
cats: 'meow',
dogs: undefined,
opossums: 'false',
birds: undefined,
};
const objectWithNull = {
cats: 'meow',
dogs: null as any,
opossums: 'false',
};
// Undefined values should be filtered out
t.is(await ky(server.url, {searchParams: objectWithUndefined}).text(), '?cats=meow&opossums=false');
// Null values should be preserved as string "null"
t.is(await ky(server.url, {searchParams: objectWithNull}).text(), '?cats=meow&dogs=null&opossums=false');
});
test('merges searchParams with input URL', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url);
});
const response = await ky(`${server.url}?foo=1`, {
searchParams: {bar: '2'},
});
const url = await response.text();
t.true(url.includes('foo=1'), `URL should contain foo=1, got: ${url}`);
t.true(url.includes('bar=2'), `URL should contain bar=2, got: ${url}`);
});
test('searchParams with undefined deletes input URL searchParams', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url);
});
const response = await ky(`${server.url}?foo=1&bar=2&qux=3`, {
// @ts-expect-error - we test that explicitly undefined value is handled
searchParams: {foo: undefined, baz: '3', qux: 'undefined'},
});
const url = await response.text();
t.false(url.includes('foo=1'), `URL should not contain foo=1, got: ${url}`);
t.true(url.includes('bar=2'), `URL should contain bar=2, got: ${url}`);
t.true(url.includes('baz=3'), `URL should contain baz=3, got: ${url}`);
t.true(url.includes('qux=undefined'), `URL should contain qux=undefined, got: ${url}`);
});
test('merges searchParams with explicitly undefined deep options', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url);
});
const api = ky.create({searchParams: new URLSearchParams({a: '1', b: '2'})});
const response = await api.get(`${server.url}?z=0`, {
// @ts-expect-error - testing undefined value
searchParams: {b: undefined, c: '3'},
});
const url = await response.text();
t.true(url.includes('z=0'), `URL should contain z=0, got: ${url}`);
t.true(url.includes('a=1'), `URL should contain a=1, got: ${url}`);
t.false(url.includes('b=2'), `URL should not contain b=2, got: ${url}`);
t.true(url.includes('c=3'), `URL should contain c=3, got: ${url}`);
});
test('merges plain object searchParams with URLSearchParams', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url);
});
const client = ky.create({searchParams: {api: '123'}});
const response = await client.get(server.url, {
searchParams: new URLSearchParams({_limit_: '1'}),
});
const url = await response.text();
t.true(url.includes('api=123'), `URL should contain api=123, got: ${url}`);
t.true(url.includes('_limit_=1'), `URL should contain _limit_=1, got: ${url}`);
t.false(url.includes('[object Object]'), `URL should not contain [object Object], got: ${url}`);
t.false(url.includes('headers'), `URL should not contain 'headers', got: ${url}`);
});
test('merges URLSearchParams with plain object searchParams', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url);
});
const client = ky.create({searchParams: new URLSearchParams({api: '123'})});
const response = await client.get(server.url, {
searchParams: {_limit_: '1'},
});
const url = await response.text();
t.true(url.includes('api=123'), `URL should contain api=123, got: ${url}`);
t.true(url.includes('_limit_=1'), `URL should contain _limit_=1, got: ${url}`);
t.false(url.includes('[object Object]'), `URL should not contain [object Object], got: ${url}`);
});
test('merges URLSearchParams with URLSearchParams', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url);
});
const client = ky.create({searchParams: new URLSearchParams({api: '123'})});
const response = await client.get(server.url, {
searchParams: new URLSearchParams({_limit_: '1'}),
});
const url = await response.text();
t.true(url.includes('api=123'), `URL should contain api=123, got: ${url}`);
t.true(url.includes('_limit_=1'), `URL should contain _limit_=1, got: ${url}`);
t.false(url.includes('[object Object]'), `URL should not contain [object Object], got: ${url}`);
});
test('merges searchParams with duplicate keys', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url);
});
const client = ky.create({searchParams: new URLSearchParams({filter: 'active'})});
const response = await client.get(server.url, {
searchParams: new URLSearchParams({filter: 'recent', _limit_: '10'}),
});
const urlString = await response.text();
const url = new URL(urlString, server.url);
const filterValues = url.searchParams.getAll('filter');
t.deepEqual(filterValues.sort(), ['active', 'recent'], `Both filter values should be present, got: ${JSON.stringify(filterValues)}`);
t.is(url.searchParams.get('_limit_'), '10', `URL should contain _limit_=10, got: ${urlString}`);
t.false(urlString.includes('[object Object]'), `URL should not contain [object Object], got: ${urlString}`);
});
test('deletes merged search params even when all additions are removed by undefined', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url);
});
const api = ky.create({searchParams: {foo: '1', bar: '2'}});
const response = await api.get(`${server.url}?foo=from-url&bar=from-url&keep=1`, {
// @ts-expect-error - testing undefined value
searchParams: {foo: undefined, bar: undefined},
});
const url = new URL(await response.text(), server.url);
t.false(url.searchParams.has('foo'));
t.false(url.searchParams.has('bar'));
t.is(url.searchParams.get('keep'), '1');
});
test('request searchParams undefined removes merged keys but keeps unrelated values', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url);
});
const api = ky.extend({searchParams: {foo: '1', bar: '2'}}).extend({searchParams: {baz: '3'}});
const response = await api.get(`${server.url}?bar=from-url&keep=1`, {
// @ts-expect-error - testing undefined value
searchParams: {foo: undefined, extra: '4'},
});
const url = new URL(await response.text(), server.url);
t.false(url.searchParams.has('foo'));
t.is(url.searchParams.get('baz'), '3');
t.is(url.searchParams.get('bar'), 'from-url');
t.is(url.searchParams.get('extra'), '4');
t.is(url.searchParams.get('keep'), '1');
});
test('string searchParams merge keeps duplicates across input URL and defaults', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url);
});
const api = ky.create({searchParams: new URLSearchParams({filter: 'active'})});
const response = await api.get(`${server.url}?filter=old&sort=old`, {
searchParams: 'filter=recent&sort=new',
});
const url = new URL(await response.text(), server.url);
t.deepEqual(url.searchParams.getAll('filter').sort(), ['active', 'old', 'recent']);
t.deepEqual(url.searchParams.getAll('sort').sort(), ['new', 'old']);
});
test('init hook can delete merged search params via undefined', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {
response.end(request.url);
});
const api = ky.create({
searchParams: {foo: '1', bar: '2'},
hooks: {
init: [
options => {
// @ts-expect-error - testing undefined value
options.searchParams = {foo: undefined, baz: '3'};
},
],
},
});
const response = await api.get(`${server.url}?bar=from-url`);
const url = new URL(await response.text(), server.url);
t.false(url.searchParams.has('foo'));
t.is(url.searchParams.get('bar'), 'from-url'); // Input URL overrides instance default
t.is(url.searchParams.get('baz'), '3'); // Added by init hook
});
test('ky.extend() searchParams layer deletion propagates through merged instances', async t => {
const server = await createHttpTestServer(t);
server.get('/', (request, response) => {