-
-
Notifications
You must be signed in to change notification settings - Fork 525
/
Copy pathindex.test.ts
2092 lines (1803 loc) · 62.7 KB
/
index.test.ts
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 { HttpResponse, type StrictResponse } from "msw";
import { afterAll, beforeAll, describe, expect, expectTypeOf, it } from "vitest";
import createClient, {
type BodySerializer,
type FetchOptions,
type Middleware,
type MiddlewareCallbackParams,
type QuerySerializerOptions,
} from "../src/index.js";
import { server, baseUrl, useMockRequestHandler, toAbsoluteURL } from "./fixtures/mock-server.js";
import type { paths } from "./fixtures/api.js";
beforeAll(() => {
server.listen({
onUnhandledRequest: (request) => {
throw new Error(`No request handler found for ${request.method} ${request.url}`);
},
});
});
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
describe("client", () => {
it("generates all proper functions", () => {
const client = createClient<paths>();
expect(client).toHaveProperty("GET");
expect(client).toHaveProperty("PUT");
expect(client).toHaveProperty("POST");
expect(client).toHaveProperty("DELETE");
expect(client).toHaveProperty("OPTIONS");
expect(client).toHaveProperty("HEAD");
expect(client).toHaveProperty("PATCH");
expect(client).toHaveProperty("TRACE");
});
describe("TypeScript checks", () => {
it("marks data or error as undefined, but never both", async () => {
const client = createClient<paths>({
baseUrl,
});
// data
useMockRequestHandler({
baseUrl,
method: "get",
path: "/string-array",
status: 200,
body: ["one", "two", "three"],
});
const dataRes = await client.GET("/string-array");
// … is initially possibly undefined
// @ts-expect-error
expect(dataRes.data[0]).toBe("one");
// … is present if error is undefined
if (!dataRes.error) {
expect(dataRes.data[0]).toBe("one");
} else {
expect(() => dataRes.error.code).toThrow(); // type test: assert inverse of above infers type correctly
}
// … means data is undefined
if (dataRes.data) {
// @ts-expect-error
expect(() => dataRes.error.message).toThrow();
} else {
// @ts-expect-error
expect(() => dataRes.data[0]).toThrow(); // type test: assert inverse of above infers type correctly
}
// error
useMockRequestHandler({
baseUrl,
method: "get",
path: "/string-array",
status: 500,
body: { code: 500, message: "Something went wrong" },
});
const errorRes = await client.GET("/string-array");
// … is initially possibly undefined
// @ts-expect-error
expect(errorRes.error.message).toBe("Something went wrong");
// … is present if error is undefined
if (!errorRes.data) {
expect(errorRes.error.message).toBe("Something went wrong");
}
// … means data is undefined
if (errorRes.error) {
// @ts-expect-error
expect(() => errorRes.data[0]).toThrow();
}
});
test("infers correct data type on mismatched media", async () => {
const client = createClient<paths>({ baseUrl });
const result = await client.GET("/mismatched-data");
if (result.data) {
expectTypeOf(result.data).toEqualTypeOf<
| {
email: string;
age?: number;
avatar?: string;
created_at: number;
updated_at: number;
}
| {
title: string;
body: string;
publish_date?: number;
}
>();
} else {
expectTypeOf(result.error).extract<{ code: number }>().toEqualTypeOf<{ code: number; message: string }>();
expectTypeOf(result.error).exclude<{ code: number }>().toEqualTypeOf<never>();
}
});
test("infers correct error type on mismatched media", async () => {
const client = createClient<paths>({ baseUrl });
const result = await client.GET("/mismatched-errors");
if (result.data) {
expectTypeOf(result.data).toEqualTypeOf<{
email: string;
age?: number;
avatar?: string;
created_at: number;
updated_at: number;
}>();
} else {
expectTypeOf(result.data).toBeUndefined();
expectTypeOf(result.error).extract<{ code: number }>().toEqualTypeOf<{ code: number; message: string }>();
expectTypeOf(result.error).exclude<{ code: number }>().toEqualTypeOf<never>();
}
});
describe("params", () => {
describe("path", () => {
it("typechecks", async () => {
const client = createClient<paths>({
baseUrl,
});
useMockRequestHandler({
baseUrl,
method: "get",
path: "/blogposts/:post_id",
status: 200,
body: { message: "OK" },
});
// expect error on missing 'params'
// @ts-expect-error
await client.GET("/blogposts/{post_id}");
// expect error on empty params
// @ts-expect-error
await client.GET("/blogposts/{post_id}", { params: {} });
// expect error on empty params.path
// @ts-expect-error
await client.GET("/blogposts/{post_id}", { params: { path: {} } });
// expect error on mismatched type (number v string)
await client.GET("/blogposts/{post_id}", {
// @ts-expect-error
params: { path: { post_id: 1234 } },
});
// expect error on unknown property in 'params'
await client.GET("/blogposts/{post_id}", {
params: {
// @ts-expect-error
TODO: "this should be an error",
},
});
// (no error)
let calledPostId = "";
useMockRequestHandler<{ post_id: string }>({
baseUrl,
method: "get",
path: "/blogposts/:post_id",
handler: ({ params }) => {
calledPostId = params.post_id;
return HttpResponse.json({ message: "OK" }, { status: 200 });
},
});
await client.GET("/blogposts/{post_id}", {
params: { path: { post_id: "1234" } },
});
// expect param passed correctly
expect(calledPostId).toBe("1234");
});
it("serializes", async () => {
const client = createClient<paths>({
baseUrl,
});
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/path-params/*",
});
await client.GET(
"/path-params/{simple_primitive}/{simple_obj_flat}/{simple_arr_flat}/{simple_obj_explode*}/{simple_arr_explode*}/{.label_primitive}/{.label_obj_flat}/{.label_arr_flat}/{.label_obj_explode*}/{.label_arr_explode*}/{;matrix_primitive}/{;matrix_obj_flat}/{;matrix_arr_flat}/{;matrix_obj_explode*}/{;matrix_arr_explode*}",
{
params: {
path: {
simple_primitive: "simple",
simple_obj_flat: { a: "b", c: "d" },
simple_arr_flat: [1, 2, 3],
simple_obj_explode: { e: "f", g: "h" },
simple_arr_explode: [4, 5, 6],
label_primitive: "label",
label_obj_flat: { a: "b", c: "d" },
label_arr_flat: [1, 2, 3],
label_obj_explode: { e: "f", g: "h" },
label_arr_explode: [4, 5, 6],
matrix_primitive: "matrix",
matrix_obj_flat: { a: "b", c: "d" },
matrix_arr_flat: [1, 2, 3],
matrix_obj_explode: { e: "f", g: "h" },
matrix_arr_explode: [4, 5, 6],
},
},
},
);
expect(getRequestUrl().pathname).toBe(
`/path-params/${[
// simple
"simple",
"a,b,c,d",
"1,2,3",
"e=f,g=h",
"4,5,6",
// label
".label",
".a,b,c,d",
".1,2,3",
".e=f.g=h",
".4.5.6",
// matrix
";matrix_primitive=matrix",
";matrix_obj_flat=a,b,c,d",
";matrix_arr_flat=1,2,3",
";e=f;g=h",
";matrix_arr_explode=4;matrix_arr_explode=5;matrix_arr_explode=6",
].join("/")}`,
);
});
it("escapes reserved characters in path segment", async () => {
const client = createClient<paths>({ baseUrl });
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/blogposts/*",
});
await client.GET("/blogposts/{post_id}", {
params: { path: { post_id: ";/?:@&=+$,# " } },
});
// expect post_id to be encoded properly
const url = getRequestUrl();
expect(url.pathname).toBe("/blogposts/%3B%2F%3F%3A%40%26%3D%2B%24%2C%23%20");
});
it("does not escape allowed characters in path segment", async () => {
const client = createClient<paths>({ baseUrl });
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/blogposts/*",
});
const postId = "aAzZ09-_.!~*'()";
await client.GET("/blogposts/{post_id}", {
params: { path: { post_id: postId } },
});
// expect post_id to stay unchanged
const url = getRequestUrl();
expect(url.pathname).toBe(`/blogposts/${postId}`);
});
it("allows UTF-8 characters", async () => {
const client = createClient<paths>({ baseUrl });
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/blogposts/*",
});
await client.GET("/blogposts/{post_id}", {
params: { path: { post_id: "🥴" } },
});
// expect post_id to be encoded properly
const url = getRequestUrl();
expect(url.pathname).toBe("/blogposts/%F0%9F%A5%B4");
});
});
it("header", async () => {
const client = createClient<paths>({ baseUrl });
useMockRequestHandler({
baseUrl,
method: "get",
path: "/header-params",
handler: ({ request }) => {
const header = request.headers.get("x-required-header");
if (header !== "correct") {
return HttpResponse.json(
{ code: 500, message: "missing correct header" },
{ status: 500 },
) as StrictResponse<any>;
}
return HttpResponse.json({ status: header }, { status: 200, headers: request.headers });
},
});
// expect error on missing header
// @ts-expect-error
await client.GET("/header-params");
// expect error on incorrect header
await client.GET("/header-params", {
// @ts-expect-error
params: { header: { foo: "bar" } },
});
// expect error on mismatched type
await client.GET("/header-params", {
// @ts-expect-error
params: { header: { "x-required-header": true } },
});
// (no error)
const response = await client.GET("/header-params", {
params: { header: { "x-required-header": "correct" } },
});
// expect param passed correctly
expect(response.response.headers.get("x-required-header")).toBe("correct");
});
describe("query", () => {
describe("querySerializer", () => {
it("primitives", async () => {
const client = createClient<paths>({ baseUrl });
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/query-params*",
});
await client.GET("/query-params", {
params: {
query: { string: "string", number: 0, boolean: false },
},
});
expect(getRequestUrl().search).toBe("?string=string&number=0&boolean=false");
});
it("array params (empty)", async () => {
const client = createClient<paths>({ baseUrl });
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/query-params*",
});
await client.GET("/query-params", {
params: {
query: { array: [] },
},
});
const url = getRequestUrl();
expect(url.pathname).toBe("/query-params");
expect(url.search).toBe("");
});
it("empty/null params", async () => {
const client = createClient<paths>({ baseUrl });
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/query-params*",
});
await client.GET("/query-params", {
params: {
query: { string: undefined, number: null as any },
},
});
const url = getRequestUrl();
expect(url.pathname).toBe("/query-params");
expect(url.search).toBe("");
});
describe("array", () => {
it.each([
[
"form",
{
given: { style: "form", explode: false },
want: "array=1,2,3&boolean=true",
},
],
[
"form (explode)",
{
given: { style: "form", explode: true },
want: "array=1&array=2&array=3&boolean=true",
},
],
[
"spaceDelimited",
{
given: { style: "spaceDelimited", explode: false },
want: "array=1%202%203&boolean=true",
},
],
[
"spaceDelimited (explode)",
{
given: { style: "spaceDelimited", explode: true },
want: "array=1&array=2&array=3&boolean=true",
},
],
[
"pipeDelimited",
{
given: { style: "pipeDelimited", explode: false },
want: "array=1|2|3&boolean=true",
},
],
[
"pipeDelimited (explode)",
{
given: { style: "pipeDelimited", explode: true },
want: "array=1&array=2&array=3&boolean=true",
},
],
] as [
string,
{
given: NonNullable<QuerySerializerOptions["array"]>;
want: string;
},
][])("%s", async (_, { given, want }) => {
const client = createClient<paths>({
baseUrl,
querySerializer: { array: given },
});
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/query-params*",
});
await client.GET("/query-params", {
params: {
query: { array: ["1", "2", "3"], boolean: true },
},
});
const url = getRequestUrl();
// skip leading '?'
expect(url.search.substring(1)).toBe(want);
});
});
describe("object", () => {
it.each([
[
"form",
{
given: { style: "form", explode: false },
want: "object=foo,bar,bar,baz&boolean=true",
},
],
[
"form (explode)",
{
given: { style: "form", explode: true },
want: "foo=bar&bar=baz&boolean=true",
},
],
[
"deepObject",
{
given: { style: "deepObject", explode: false }, // note: `false` not supported; same as `true`
want: "object[foo]=bar&object[bar]=baz&boolean=true",
},
],
[
"deepObject (explode)",
{
given: { style: "deepObject", explode: true },
want: "object[foo]=bar&object[bar]=baz&boolean=true",
},
],
] as [
string,
{
given: NonNullable<QuerySerializerOptions["object"]>;
want: string;
},
][])("%s", async (_, { given, want }) => {
const client = createClient<paths>({
baseUrl,
querySerializer: { object: given },
});
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/query-params*",
});
await client.GET("/query-params", {
params: {
query: { object: { foo: "bar", bar: "baz" }, boolean: true },
},
});
const url = getRequestUrl();
// skip leading '?'
expect(url.search.substring(1)).toBe(want);
});
});
it("allowReserved", async () => {
const client = createClient<paths>({
baseUrl,
querySerializer: { allowReserved: true },
});
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/query-params*",
});
await client.GET("/query-params", {
params: {
query: {
string: "bad/character🐶",
},
},
});
expect(getRequestUrl().search).toBe("?string=bad/character%F0%9F%90%B6");
expect(getRequestUrl().searchParams.get("string")).toBe("bad/character🐶");
await client.GET("/query-params", {
params: {
query: {
string: "bad/character🐶",
},
},
querySerializer: {
allowReserved: false,
},
});
expect(getRequestUrl().search).toBe("?string=bad%2Fcharacter%F0%9F%90%B6");
expect(getRequestUrl().searchParams.get("string")).toBe("bad/character🐶");
});
describe("function", () => {
it("global default", async () => {
const client = createClient<paths>({
baseUrl,
querySerializer: (q) => `alpha=${q.version}&beta=${q.format}`,
});
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/blogposts/:post_id",
});
await client.GET("/blogposts/{post_id}", {
params: {
path: { post_id: "my-post" },
query: { version: 2, format: "json" },
},
});
const url = getRequestUrl();
expect(url.pathname + url.search).toBe("/blogposts/my-post?alpha=2&beta=json");
});
it("per-request", async () => {
const client = createClient<paths>({
baseUrl,
querySerializer: () => "query",
});
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/blogposts/:post_id",
});
await client.GET("/blogposts/{post_id}", {
params: {
path: { post_id: "my-post" },
query: { version: 2, format: "json" },
},
querySerializer: (q) => `alpha=${q.version}&beta=${q.format}`,
});
const url = getRequestUrl();
expect(url.pathname + url.search).toBe("/blogposts/my-post?alpha=2&beta=json");
});
});
it("ignores leading ? characters", async () => {
const client = createClient<paths>({
baseUrl,
querySerializer: () => "?query",
});
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/blogposts/:post_id",
});
await client.GET("/blogposts/{post_id}", {
params: {
path: { post_id: "my-post" },
query: { version: 2, format: "json" },
},
});
const url = getRequestUrl();
expect(url.pathname + url.search).toBe("/blogposts/my-post?query");
});
});
});
});
describe("body", () => {
// these are pure type tests; no runtime assertions needed
it("requires necessary requestBodies", async () => {
const client = createClient<paths>({ baseUrl });
useMockRequestHandler({
baseUrl,
method: "put",
path: "/blogposts",
});
// expect error on missing `body`
// @ts-expect-error
await client.PUT("/blogposts");
// expect error on missing fields
// @ts-expect-error
await client.PUT("/blogposts", { body: { title: "Foo" } });
// expect present body to be good enough (all fields optional)
// (no error)
await client.PUT("/blogposts", {
body: {
title: "Foo",
body: "Bar",
publish_date: new Date("2023-04-01T12:00:00Z").getTime(),
},
});
});
it("requestBody (inline)", async () => {
const client = createClient<paths>({ baseUrl });
useMockRequestHandler({
baseUrl,
method: "put",
path: "/blogposts-optional-inline",
status: 201,
});
// expect error on wrong body type
await client.PUT("/blogposts-optional-inline", {
// @ts-expect-error
body: { error: true },
});
// (no error)
await client.PUT("/blogposts-optional-inline", {
body: {
title: "",
publish_date: 3,
body: "",
},
});
});
it("requestBody with required: false", async () => {
const client = createClient<paths>({ baseUrl });
useMockRequestHandler({
baseUrl,
method: "put",
path: "/blogposts-optional",
status: 201,
});
// assert missing `body` doesn’t raise a TS error
await client.PUT("/blogposts-optional");
// assert error on type mismatch
// @ts-expect-error
await client.PUT("/blogposts-optional", { body: { error: true } });
// (no error)
await client.PUT("/blogposts-optional", {
body: {
title: "",
publish_date: 3,
body: "",
},
});
});
});
});
describe("options", () => {
it("baseUrl", async () => {
let client = createClient<paths>({ baseUrl });
const { getRequestUrl } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/self",
status: 200,
body: { message: "OK" },
});
await client.GET("/self");
// assert baseUrl and path mesh as expected
expect(getRequestUrl().href).toBe(toAbsoluteURL("/self"));
client = createClient<paths>({ baseUrl });
await client.GET("/self");
// assert trailing '/' was removed
expect(getRequestUrl().href).toBe(toAbsoluteURL("/self"));
});
describe("headers", () => {
it("persist", async () => {
const headers: HeadersInit = { Authorization: "Bearer secrettoken" };
const client = createClient<paths>({ headers, baseUrl });
const { getRequest } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/self",
status: 200,
body: { email: "[email protected]" },
});
await client.GET("/self");
// assert default headers were passed
expect(getRequest().headers).toEqual(
new Headers({
...headers, // assert new header got passed
"Content-Type": "application/json", // probably doesn’t need to get tested, but this was simpler than writing lots of code to ignore these
}),
);
});
it("can be overridden", async () => {
const client = createClient<paths>({
baseUrl,
headers: { "Cache-Control": "max-age=10000000" },
});
const { getRequest } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/self",
status: 200,
body: { email: "[email protected]" },
});
await client.GET("/self", {
params: {},
headers: { "Cache-Control": "no-cache" },
});
// assert default headers were passed
expect(getRequest().headers).toEqual(
new Headers({
"Cache-Control": "no-cache",
"Content-Type": "application/json",
}),
);
});
it("can be unset", async () => {
const client = createClient<paths>({
baseUrl,
headers: { "Content-Type": null },
});
const { getRequest } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/self",
status: 200,
body: { email: "[email protected]" },
});
await client.GET("/self", { params: {} });
// assert default headers were passed
expect(getRequest().headers).toEqual(new Headers());
});
it("supports arrays", async () => {
const client = createClient<paths>({ baseUrl });
const list = ["one", "two", "three"];
const { getRequest } = useMockRequestHandler({
baseUrl,
method: "get",
path: "/self",
status: 200,
body: {},
});
await client.GET("/self", { headers: { list } });
expect(getRequest().headers.get("list")).toEqual(list.join(", "));
});
});
describe("fetch", () => {
it("createClient", async () => {
function createCustomFetch(data: any) {
const response = {
clone: () => ({ ...response }),
headers: new Headers(),
json: async () => data,
status: 200,
ok: true,
} as Response;
return async () => Promise.resolve(response);
}
const customFetch = createCustomFetch({ works: true });
const client = createClient<paths>({ fetch: customFetch, baseUrl });
const { data } = await client.GET("/self");
// assert data was returned from custom fetcher
expect(data).toEqual({ works: true });
// TODO: do we need to assert nothing was called?
// msw should throw an error if there was an unused handler
});
it("per-request", async () => {
function createCustomFetch(data: any) {
const response = {
clone: () => ({ ...response }),
headers: new Headers(),
json: async () => data,
status: 200,
ok: true,
} as Response;
return async () => Promise.resolve(response);
}
const fallbackFetch = createCustomFetch({ fetcher: "fallback" });
const overrideFetch = createCustomFetch({ fetcher: "override" });
const client = createClient<paths>({ fetch: fallbackFetch, baseUrl });
// assert override function was called
const fetch1 = await client.GET("/self", { fetch: overrideFetch });
expect(fetch1.data).toEqual({ fetcher: "override" });
// assert fallback function still persisted (and wasn’t overridden)
const fetch2 = await client.GET("/self");
expect(fetch2.data).toEqual({ fetcher: "fallback" });
// TODO: do we need to assert nothing was called?
// msw should throw an error if there was an unused handler
});
});
describe("middleware", () => {
it("receives a UUID per-request", async () => {
const client = createClient<paths>({ baseUrl });
const requestIDs: string[] = [];
const responseIDs: string[] = [];
client.use({
async onRequest({ id }) {
requestIDs.push(id);
},
async onResponse({ id }) {
responseIDs.push(id);
},
});
await client.GET("/self");
await client.GET("/self");
await client.GET("/self");
// assert IDs matched between requests and responses
expect(requestIDs[0]).toBe(responseIDs[0]);
expect(requestIDs[1]).toBe(responseIDs[1]);
expect(requestIDs[2]).toBe(responseIDs[2]);
// assert IDs were unique
expect(requestIDs[0] !== requestIDs[1] && requestIDs[1] !== requestIDs[2]).toBe(true);
});
it("can modify request", async () => {
const client = createClient<paths>({ baseUrl });
client.use({
async onRequest({ request }) {
return new Request("https://foo.bar/api/v1", {
...request,
method: "OPTIONS",
headers: { foo: "bar" },
});
},
});
const { getRequest } = useMockRequestHandler({
baseUrl,
method: "options",
path: "https://foo.bar/api/v1",
status: 200,
body: {},
});
await client.GET("/self");
const req = getRequest();
expect(req.url).toBe("https://foo.bar/api/v1");
expect(req.method).toBe("OPTIONS");
expect(req.headers.get("foo")).toBe("bar");
});
it("can modify response", async () => {
const toUnix = (date: string) => new Date(date).getTime();
const rawBody = {
email: "[email protected]",
created_at: "2024-01-01T00:00:00Z",
updated_at: "2024-01-20T00:00:00Z",
};
useMockRequestHandler({
baseUrl,
method: "get",
path: "/self",
status: 200,
body: rawBody,
headers: { foo: "bar" },
});
const client = createClient<paths>({ baseUrl });
client.use({
// convert date string to unix time
async onResponse({ response }) {
const body = await response.json();
body.created_at = toUnix(body.created_at);
body.updated_at = toUnix(body.updated_at);