-
-
Notifications
You must be signed in to change notification settings - Fork 529
/
Copy pathv7-beta.test.ts
911 lines (777 loc) · 28.6 KB
/
v7-beta.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
import { atom, computed } from "nanostores";
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
// @ts-expect-error
import createFetchMock from "vitest-fetch-mock";
import createClient from "../src/index.js";
import type { paths } from "./v7-beta.js";
// Note
// This is a copy of index.test.ts, but uses generated types from openapi-typescript@7 (beta).
// This tests upcoming compatibility until openapi-typescript@7 is stable and the two tests
// merged together.
const fetchMocker = createFetchMock(vi);
beforeAll(() => {
fetchMocker.enableMocks();
});
afterEach(() => {
fetchMocker.resetMocks();
});
interface MockResponse {
headers?: Record<string, string>;
status: number;
body: any;
}
function mockFetch(res: MockResponse) {
fetchMocker.mockResponse(() => res);
}
function mockFetchOnce(res: MockResponse) {
fetchMocker.mockResponseOnce(() => res);
}
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>();
// data
mockFetchOnce({
status: 200,
body: JSON.stringify(["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");
}
// … means data is undefined
if (dataRes.data) {
// @ts-expect-error
expect(() => dataRes.error.message).toThrow();
}
// error
mockFetchOnce({
status: 500,
body: JSON.stringify({ 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();
}
});
describe("params", () => {
it("path", async () => {
const client = createClient<paths>({ baseUrl: "https://myapi.com/v1" });
mockFetch({ status: 200, body: JSON.stringify({ message: "OK" }) });
// expect error on missing 'params'
await client.GET("/blogposts/{post_id}", {
// @ts-expect-error
TODO: "this should be an error",
});
// expect error on empty params
await client.GET("/blogposts/{post_id}", {
// @ts-expect-error
params: { TODO: "this should be an error" },
});
// 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 } },
});
// (no error)
await client.GET("/blogposts/{post_id}", {
params: { path: { post_id: "1234" } },
});
// expect param passed correctly
const lastCall =
fetchMocker.mock.calls[fetchMocker.mock.calls.length - 1];
expect(lastCall[0]).toBe("https://myapi.com/v1/blogposts/1234");
});
it("header", async () => {
const client = createClient<paths>({ baseUrl: "https://myapi.com/v1" });
mockFetch({ status: 200, body: JSON.stringify({ status: "success" }) });
// expet error on missing header
// @ts-expect-error
await client.GET("/header-params", { TODO: "this should be an error" });
// 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)
await client.GET("/header-params", {
params: { header: { "x-required-header": "correct" } },
});
// expect param passed correctly
const lastCall =
fetchMocker.mock.calls[fetchMocker.mock.calls.length - 1];
expect(lastCall[1].headers.get("x-required-header")).toBe("correct");
});
describe("query", () => {
it("primitives", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.GET("/query-params", {
params: {
query: { string: "string", number: 0, boolean: false },
},
});
expect(fetchMocker.mock.calls[0][0]).toBe(
"/query-params?string=string&number=0&boolean=false",
);
});
it("array params", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.GET("/query-params", {
params: {
query: { array: ["one", "two", "three"] },
},
});
expect(fetchMocker.mock.calls[0][0]).toBe(
"/query-params?array=one&array=two&array=three",
);
});
it("array params (empty)", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.GET("/query-params", {
params: {
query: { array: [] },
},
});
expect(fetchMocker.mock.calls[0][0]).toBe("/query-params");
});
it("object params", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.GET("/query-params", {
params: {
query: {
object: { foo: "foo", deep: { nested: { object: "bar" } } },
},
},
});
expect(fetchMocker.mock.calls[0][0]).toBe(
"/query-params?object[foo]=foo&object[deep][nested][object]=bar",
);
});
it("empty/null params", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.GET("/query-params", {
params: {
query: { string: undefined, number: null as any },
},
});
expect(fetchMocker.mock.calls[0][0]).toBe("/query-params");
});
describe("querySerializer", () => {
it("custom", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
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}`,
});
expect(fetchMocker.mock.calls[0][0]).toBe(
"/blogposts/my-post?alpha=2&beta=json",
);
});
it("applies global serializer", async () => {
const client = createClient<paths>({
querySerializer: (q) => `alpha=${q.version}&beta=${q.format}`,
});
mockFetchOnce({ status: 200, body: "{}" });
await client.GET("/blogposts/{post_id}", {
params: {
path: { post_id: "my-post" },
query: { version: 2, format: "json" },
},
});
expect(fetchMocker.mock.calls[0][0]).toBe(
"/blogposts/my-post?alpha=2&beta=json",
);
});
it("overrides global serializer if provided", async () => {
const client = createClient<paths>({
querySerializer: () => "query",
});
mockFetchOnce({ status: 200, body: "{}" });
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}`,
});
expect(fetchMocker.mock.calls[0][0]).toBe(
"/blogposts/my-post?alpha=2&beta=json",
);
});
});
});
});
describe("body", () => {
// these are pure type tests; no runtime assertions needed
/* eslint-disable vitest/expect-expect */
it("requires necessary requestBodies", async () => {
const client = createClient<paths>({ baseUrl: "https://myapi.com/v1" });
mockFetch({ status: 200, body: JSON.stringify({ message: "OK" }) });
// 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 () => {
mockFetch({ status: 201, body: "{}" });
const client = createClient<paths>();
// 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 () => {
mockFetch({ status: 201, body: "{}" });
const client = createClient<paths>();
// 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: "",
},
});
});
});
/* eslint-enable vitest/expect-expect */
});
describe("options", () => {
it("respects baseUrl", async () => {
let client = createClient<paths>({ baseUrl: "https://myapi.com/v1" });
mockFetch({ status: 200, body: JSON.stringify({ message: "OK" }) });
await client.GET("/self");
// assert baseUrl and path mesh as expected
expect(fetchMocker.mock.calls[0][0]).toBe("https://myapi.com/v1/self");
client = createClient<paths>({ baseUrl: "https://myapi.com/v1/" });
await client.GET("/self");
// assert trailing '/' was removed
expect(fetchMocker.mock.calls[1][0]).toBe("https://myapi.com/v1/self");
});
it("preserves default headers", async () => {
const headers: HeadersInit = { Authorization: "Bearer secrettoken" };
const client = createClient<paths>({ headers });
mockFetchOnce({
status: 200,
body: JSON.stringify({ email: "[email protected]" }),
});
await client.GET("/self");
// assert default headers were passed
const options = fetchMocker.mock.calls[0][1];
expect(options?.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("allows override headers", async () => {
const client = createClient<paths>({
headers: { "Cache-Control": "max-age=10000000" },
});
mockFetchOnce({
status: 200,
body: JSON.stringify({ email: "[email protected]" }),
});
await client.GET("/self", {
params: {},
headers: { "Cache-Control": "no-cache" },
});
// assert default headers were passed
const options = fetchMocker.mock.calls[0][1];
expect(options?.headers).toEqual(
new Headers({
"Cache-Control": "no-cache",
"Content-Type": "application/json",
}),
);
});
it("allows unsetting headers", async () => {
const client = createClient<paths>({ headers: { "Content-Type": null } });
mockFetchOnce({
status: 200,
body: JSON.stringify({ email: "[email protected]" }),
});
await client.GET("/self", { params: {} });
// assert default headers were passed
const options = fetchMocker.mock.calls[0][1];
expect(options?.headers).toEqual(new Headers());
});
it("accepts a custom fetch function on 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 });
mockFetchOnce({ status: 200, body: "{}" });
const client = createClient<paths>({ fetch: customFetch });
const { data } = await client.GET("/self");
// assert data was returned from custom fetcher
expect(data).toEqual({ works: true });
// assert global fetch was never called
expect(fetchMocker).not.toHaveBeenCalled();
});
it("accepts a custom fetch function 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" });
mockFetchOnce({ status: 200, body: "{}" });
const client = createClient<paths>({ fetch: fallbackFetch });
// 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" });
// assert global fetch was never called
expect(fetchMocker).not.toHaveBeenCalled();
});
});
describe("requests", () => {
it("escapes URLs properly", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.GET("/blogposts/{post_id}", {
params: {
path: {
post_id: "post?id = 🥴",
},
},
});
// expect post_id to be encoded properly
expect(fetchMocker.mock.calls[0][0]).toBe(
"/blogposts/post%3Fid%20%3D%20%F0%9F%A5%B4",
);
});
it("multipart/form-data", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.PUT("/contact", {
body: {
name: "John Doe",
email: "[email protected]",
subject: "Test Message",
message: "This is a test message",
},
bodySerializer(body) {
const fd = new FormData();
for (const [k, v] of Object.entries(body)) {
fd.append(k, v);
}
return fd;
},
});
// expect post_id to be encoded properly
const req = fetchMocker.mock.calls[0][1];
expect(req.body).toBeInstanceOf(FormData);
// TODO: `vitest-fetch-mock` does not add the boundary to the Content-Type header like browsers do, so we expect the header to be null instead
expect((req.headers as Headers).get("Content-Type")).toBeNull();
});
});
describe("responses", () => {
it("returns empty object on 204", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 204, body: "" });
const { data, error, response } = await client.DELETE("/tag/{name}", {
params: { path: { name: "New Tag" } },
});
// assert correct data was returned
expect(data).toEqual({});
expect(response.status).toBe(204);
// assert error is empty
expect(error).toBeUndefined();
});
it("treats `default` as an error", async () => {
const client = createClient<paths>({
headers: { "Cache-Control": "max-age=10000000" },
});
mockFetchOnce({
status: 500,
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
code: 500,
message: "An unexpected error occurred",
}),
});
const { error } = await client.GET("/default-as-error");
// discard `data` object
if (!error) {
throw new Error(
"treats `default` as an error: error response should be present",
);
}
// assert `error.message` doesn’t throw TS error
expect(error.message).toBe("An unexpected error occurred");
});
describe("parseAs", () => {
it("text", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", { parseAs: "text" });
expect(data).toBe("{}");
});
it("arrayBuffer", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", {
parseAs: "arrayBuffer",
});
expect(data instanceof ArrayBuffer).toBe(true);
});
it("blob", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", { parseAs: "blob" });
// eslint-disable-next-line @typescript-eslint/no-explicit-any
expect((data as any).constructor.name).toBe("Blob");
});
it("stream", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
const { data } = await client.GET("/anyMethod", { parseAs: "stream" });
expect(data instanceof Buffer).toBe(true);
});
});
});
describe("GET()", () => {
it("sends the correct method", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.GET("/anyMethod");
expect(fetchMocker.mock.calls[0][1]?.method).toBe("GET");
});
it("sends correct options, returns success", async () => {
const mockData = {
title: "My Post",
body: "<p>This is a very good post</p>",
publish_date: new Date("2023-03-01T12:00:00Z").getTime(),
};
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: JSON.stringify(mockData) });
const { data, error, response } = await client.GET(
"/blogposts/{post_id}",
{
params: { path: { post_id: "my-post" } },
},
);
// assert correct URL was called
expect(fetchMocker.mock.calls[0][0]).toBe("/blogposts/my-post");
// assert correct data was returned
expect(data).toEqual(mockData);
expect(response.status).toBe(200);
// assert error is empty
expect(error).toBeUndefined();
});
it("sends correct options, returns error", async () => {
const mockError = { code: 404, message: "Post not found" };
const client = createClient<paths>();
mockFetchOnce({ status: 404, body: JSON.stringify(mockError) });
const { data, error, response } = await client.GET(
"/blogposts/{post_id}",
{
params: { path: { post_id: "my-post" } },
},
);
// assert correct URL was called
expect(fetchMocker.mock.calls[0][0]).toBe("/blogposts/my-post");
// assert correct method was called
expect(fetchMocker.mock.calls[0][1]?.method).toBe("GET");
// assert correct error was returned
expect(error).toEqual(mockError);
expect(response.status).toBe(404);
// assert data is empty
expect(data).toBeUndefined();
});
// note: this was a previous bug in the type inference
it("handles array-type responses", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "[]" });
const { data } = await client.GET("/blogposts", { params: {} });
if (!data) {
throw new Error("data empty");
}
// assert array type (and only array type) was inferred
expect(data.length).toBe(0);
});
it("handles literal 2XX and 4XX codes", async () => {
const client = createClient<paths>();
mockFetch({ status: 201, body: '{"status": "success"}' });
const { data, error } = await client.PUT("/media", {
body: { media: "base64", name: "myImage" },
});
if (data) {
// assert 2XX type inferred correctly
expect(data.status).toBe("success");
} else {
// assert 4XX type inferred correctly
// (this should be a dead code path but tests TS types)
expect(error.message).toBe("Error");
}
});
});
describe("POST()", () => {
it("sends the correct method", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.POST("/anyMethod");
expect(fetchMocker.mock.calls[0][1]?.method).toBe("POST");
});
it("sends correct options, returns success", async () => {
const mockData = { status: "success" };
const client = createClient<paths>();
mockFetchOnce({ status: 201, body: JSON.stringify(mockData) });
const { data, error, response } = await client.PUT("/blogposts", {
body: {
title: "New Post",
body: "<p>Best post yet</p>",
publish_date: new Date("2023-03-31T12:00:00Z").getTime(),
},
});
// assert correct URL was called
expect(fetchMocker.mock.calls[0][0]).toBe("/blogposts");
// assert correct data was returned
expect(data).toEqual(mockData);
expect(response.status).toBe(201);
// assert error is empty
expect(error).toBeUndefined();
});
it("supports sepecifying utf-8 encoding", async () => {
const mockData = { message: "My reply" };
const client = createClient<paths>();
mockFetchOnce({ status: 201, body: JSON.stringify(mockData) });
const { data, error, response } = await client.PUT("/comment", {
params: {},
body: {
message: "My reply",
replied_at: new Date("2023-03-31T12:00:00Z").getTime(),
},
});
// assert correct data was returned
expect(data).toEqual(mockData);
expect(response.status).toBe(201);
// assert error is empty
expect(error).toBeUndefined();
});
});
describe("DELETE()", () => {
it("sends the correct method", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.DELETE("/anyMethod");
expect(fetchMocker.mock.calls[0][1]?.method).toBe("DELETE");
});
it("returns empty object on 204", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 204, body: "" });
const { data, error } = await client.DELETE("/blogposts/{post_id}", {
params: {
path: { post_id: "123" },
},
});
// assert correct data was returned
expect(data).toEqual({});
// assert error is empty
expect(error).toBeUndefined();
});
it("returns empty object on Content-Length: 0", async () => {
const client = createClient<paths>();
mockFetchOnce({
headers: { "Content-Length": "0" },
status: 200,
body: "",
});
const { data, error } = await client.DELETE("/blogposts/{post_id}", {
params: {
path: { post_id: "123" },
},
});
// assert correct data was returned
expect(data).toEqual({});
// assert error is empty
expect(error).toBeUndefined();
});
});
describe("OPTIONS()", () => {
it("sends the correct method", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.OPTIONS("/anyMethod");
expect(fetchMocker.mock.calls[0][1]?.method).toBe("OPTIONS");
});
});
describe("HEAD()", () => {
it("sends the correct method", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.HEAD("/anyMethod");
expect(fetchMocker.mock.calls[0][1]?.method).toBe("HEAD");
});
});
describe("PATCH()", () => {
it("sends the correct method", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.PATCH("/anyMethod");
expect(fetchMocker.mock.calls[0][1]?.method).toBe("PATCH");
});
});
describe("TRACE()", () => {
it("sends the correct method", async () => {
const client = createClient<paths>();
mockFetchOnce({ status: 200, body: "{}" });
await client.TRACE("/anyMethod");
expect(fetchMocker.mock.calls[0][1]?.method).toBe("TRACE");
});
});
});
// test that the library behaves as expected inside commonly-used patterns
describe("examples", () => {
it("nanostores", async () => {
const token = atom<string | undefined>();
const client = computed([token], (currentToken) =>
createClient<paths>({
headers: currentToken
? { Authorization: `Bearer ${currentToken}` }
: {},
}),
);
// assert initial call is unauthenticated
mockFetchOnce({ status: 200, body: "{}" });
await client
.get()
.GET("/blogposts/{post_id}", { params: { path: { post_id: "1234" } } });
expect(
fetchMocker.mock.calls[0][1].headers.get("authorization"),
).toBeNull();
// assert after setting token, client is authenticated
const tokenVal = "abcd";
mockFetchOnce({ status: 200, body: "{}" });
await new Promise<void>((resolve) =>
setTimeout(() => {
token.set(tokenVal); // simulate promise-like token setting
resolve();
}, 0),
);
await client
.get()
.GET("/blogposts/{post_id}", { params: { path: { post_id: "1234" } } });
expect(fetchMocker.mock.calls[1][1].headers.get("authorization")).toBe(
`Bearer ${tokenVal}`,
);
});
it("proxies", async () => {
let token: string | undefined = undefined;
const baseClient = createClient<paths>();
const client = new Proxy(baseClient, {
get(_, key: keyof typeof baseClient) {
const newClient = createClient<paths>({
headers: token ? { Authorization: `Bearer ${token}` } : {},
});
return newClient[key];
},
});
// assert initial call is unauthenticated
mockFetchOnce({ status: 200, body: "{}" });
await client.GET("/blogposts/{post_id}", {
params: { path: { post_id: "1234" } },
});
expect(
fetchMocker.mock.calls[0][1].headers.get("authorization"),
).toBeNull();
// assert after setting token, client is authenticated
const tokenVal = "abcd";
mockFetchOnce({ status: 200, body: "{}" });
await new Promise<void>((resolve) =>
setTimeout(() => {
token = tokenVal; // simulate promise-like token setting
resolve();
}, 0),
);
await client.GET("/blogposts/{post_id}", {
params: { path: { post_id: "1234" } },
});
expect(fetchMocker.mock.calls[1][1].headers.get("authorization")).toBe(
`Bearer ${tokenVal}`,
);
});
});