forked from JakeChampion/fetch
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathindex.js
More file actions
1937 lines (1589 loc) · 62.9 KB
/
index.js
File metadata and controls
1937 lines (1589 loc) · 62.9 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 { Platform } from "react-native";
import { polyfill as polyfillEncoding } from "react-native-polyfill-globals/src/encoding";
import { polyfill as polyfillReadableStream } from "react-native-polyfill-globals/src/readable-stream";
import { polyfill as polyfillURL } from "react-native-polyfill-globals/src/url";
import { test } from "zora";
import delay from "delay";
import { Headers, Request, Response, fetch } from "../";
polyfillEncoding();
polyfillReadableStream();
polyfillURL();
const BASE_URL = Platform.select({
android: "http://10.0.2.2:8082",
ios: "http://localhost:8082",
});
function createBlobReader(blob) {
const reader = new FileReader();
const fileReaderReady = new Promise((resolve, reject) => {
reader.onload = function () {
resolve(reader.result);
};
reader.onerror = function () {
reject(reader.error);
};
});
return {
readAsArrayBuffer: async () => {
reader.readAsArrayBuffer(blob);
return fileReaderReady;
},
readAsText: async () => {
reader.readAsText(blob);
return fileReaderReady;
},
};
}
function readArrayBufferAsText(array) {
const decoder = new TextDecoder();
return decoder.decode(array);
}
function createTypedArrayFromText(text) {
const decoder = new TextEncoder();
return decoder.encode(text);
}
async function drainStream(stream) {
const chunks = [];
const reader = stream.getReader();
function readNextChunk() {
return reader.read().then(({ done, value }) => {
if (done) {
return chunks.reduce(
(bytes, chunk) => [...bytes, ...chunk],
[]
);
}
chunks.push(value);
return readNextChunk();
});
}
const bytes = await readNextChunk();
return new Uint8Array(bytes);
}
function allSettled(promises) {
return new Promise((resolve, reject) => {
const results = [];
function resolveWhenAllSettled() {
if (promises.length === results.length) {
resolve(results);
}
}
promises.forEach((promise) => {
promise
.then((value) => {
results.push({ status: "fulfilled", value });
})
.catch((error) => {
results.push({ status: "rejected", error });
})
.finally(resolveWhenAllSettled);
});
});
}
test("headers", (t) => {
t.test("constructor copies headers", (t) => {
const original = new Headers();
original.append("Accept", "application/json");
original.append("Accept", "text/plain");
original.append("Content-Type", "text/html");
const headers = new Headers(original);
t.eq(headers.get("Accept"), "application/json, text/plain");
t.eq(headers.get("Content-type"), "text/html");
});
t.test("constructor works with arrays", (t) => {
const array = [
["Content-Type", "text/xml"],
["Breaking-Bad", "<3"],
];
const headers = new Headers(array);
t.eq(headers.get("Content-Type"), "text/xml");
t.eq(headers.get("Breaking-Bad"), "<3");
});
t.test("headers are case insensitive", (t) => {
const headers = new Headers({ Accept: "application/json" });
t.eq(headers.get("ACCEPT"), "application/json");
t.eq(headers.get("Accept"), "application/json");
t.eq(headers.get("accept"), "application/json");
});
t.test("appends to existing", (t) => {
const headers = new Headers({ Accept: "application/json" });
t.notOk(headers.has("Content-Type"));
headers.append("Content-Type", "application/json");
t.ok(headers.has("Content-Type"));
t.eq(headers.get("Content-Type"), "application/json");
});
t.test("appends values to existing header name", (t) => {
const headers = new Headers({ Accept: "application/json" });
headers.append("Accept", "text/plain");
t.eq(headers.get("Accept"), "application/json, text/plain");
});
t.test("sets header name and value", (t) => {
const headers = new Headers();
headers.set("Content-Type", "application/json");
t.eq(headers.get("Content-Type"), "application/json");
});
t.test("returns null on no header found", (t) => {
const headers = new Headers();
t.is(headers.get("Content-Type"), null);
});
t.test("has headers that are set", (t) => {
const headers = new Headers();
headers.set("Content-Type", "application/json");
t.ok(headers.has("Content-Type"));
});
t.test("deletes headers", (t) => {
const headers = new Headers();
headers.set("Content-Type", "application/json");
t.ok(headers.has("Content-Type"));
headers.delete("Content-Type");
t.notOk(headers.has("Content-Type"));
t.is(headers.get("Content-Type"), null);
});
t.test("converts field name to string on set and get", (t) => {
const headers = new Headers();
headers.set(1, "application/json");
t.ok(headers.has("1"));
t.equal(headers.get(1), "application/json");
});
t.test("converts field value to string on set and get", (t) => {
const headers = new Headers();
headers.set("Content-Type", 1);
headers.set("X-CSRF-Token", undefined);
t.equal(headers.get("Content-Type"), "1");
t.equal(headers.get("X-CSRF-Token"), "undefined");
});
t.test("throws TypeError on invalid character in field name", (t) => {
t.throws(() => {
new Headers({ "[Accept]": "application/json" });
}, TypeError);
t.throws(() => {
new Headers({ "Accept:": "application/json" });
}, TypeError);
t.throws(() => {
const headers = new Headers();
headers.set({ field: "value" }, "application/json");
}, TypeError);
t.throws(() => {
new Headers({ "": "application/json" });
}, TypeError);
});
t.test("is iterable with forEach", (t) => {
const headers = new Headers();
headers.append("Accept", "application/json");
headers.append("Accept", "text/plain");
headers.append("Content-Type", "text/html");
const results = [];
headers.forEach((value, name, object) => {
results.push({ value, name, object });
});
t.eq(results.length, 2);
t.eq(
{
name: "accept",
value: "application/json, text/plain",
object: headers,
},
results[0]
);
t.eq(
{
name: "content-type",
value: "text/html",
object: headers,
},
results[1]
);
});
t.test("forEach accepts second thisArg argument", (t) => {
const headers = new Headers({ Accept: "application/json" });
const thisArg = {};
headers.forEach(function () {
t.is(this, thisArg);
}, thisArg);
});
t.test("is iterable with keys", (t) => {
const headers = new Headers();
headers.append("Accept", "application/json");
headers.append("Accept", "text/plain");
headers.append("Content-Type", "text/html");
const iterator = headers.keys();
t.eq({ done: false, value: "accept" }, iterator.next());
t.eq({ done: false, value: "content-type" }, iterator.next());
t.eq({ done: true, value: undefined }, iterator.next());
});
t.test("is iterable with values", (t) => {
const headers = new Headers();
headers.append("Accept", "application/json");
headers.append("Accept", "text/plain");
headers.append("Content-Type", "text/html");
var iterator = headers.values();
t.eq(
{ done: false, value: "application/json, text/plain" },
iterator.next()
);
t.eq({ done: false, value: "text/html" }, iterator.next());
t.eq({ done: true, value: undefined }, iterator.next());
});
t.test("is iterable with entries", (t) => {
const headers = new Headers();
headers.append("Accept", "application/json");
headers.append("Accept", "text/plain");
headers.append("Content-Type", "text/html");
const iterator = headers.entries();
t.eq(
{ done: false, value: ["accept", "application/json, text/plain"] },
iterator.next()
);
t.eq(
{ done: false, value: ["content-type", "text/html"] },
iterator.next()
);
t.eq({ done: true, value: undefined }, iterator.next());
});
t.test("headers is an iterator which returns entries iterator", (t) => {
const headers = new Headers();
headers.append("Accept", "application/json");
headers.append("Accept", "text/plain");
headers.append("Content-Type", "text/html");
const iterator = headers[Symbol.iterator]();
t.eq(
{ done: false, value: ["accept", "application/json, text/plain"] },
iterator.next()
);
t.eq(
{ done: false, value: ["content-type", "text/html"] },
iterator.next()
);
t.eq({ done: true, value: undefined }, iterator.next());
});
});
test("request", (t) => {
t.test("should throw when called without constructor", (t) => {
t.throws(() => {
Request("https://fetch.spec.whatwg.org/");
});
});
t.test("construct with string url", (t) => {
const req = new Request("https://fetch.spec.whatwg.org/");
t.eq(req.url, "https://fetch.spec.whatwg.org/");
});
t.test("construct with URL instance", (t) => {
const url = new URL("https://fetch.spec.whatwg.org/pathname");
const req = new Request(url);
t.eq(req.url.toString(), "https://fetch.spec.whatwg.org/pathname");
});
t.test("construct with non-request object", (t) => {
const url = {
toString: () => {
return "https://fetch.spec.whatwg.org/";
},
};
const req = new Request(url);
t.eq(req.url.toString(), "https://fetch.spec.whatwg.org/");
});
t.test("construct with request", async (t) => {
const request1 = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
body: "I work out",
headers: {
accept: "application/json",
"Content-Type": "text/plain",
},
});
const request2 = new Request(request1);
const body2 = await request2.text();
t.eq(body2, "I work out");
t.eq(request2.method, "POST");
t.eq(request2.url, "https://fetch.spec.whatwg.org/");
t.eq(request2.headers.get("accept"), "application/json");
t.eq(request2.headers.get("content-type"), "text/plain");
try {
await request1.text();
t.ok(false, "original request body should have been consumed");
} catch (error) {
t.ok(
error instanceof TypeError,
"expected TypeError for already read body"
);
}
});
t.test("construct with request and override headers", (t) => {
const request1 = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
body: "I work out",
headers: {
accept: "application/json",
"X-Request-ID": "123",
},
});
const request2 = new Request(request1, {
headers: { "x-test": "42" },
});
t.eq(request2.headers.get("accept"), null);
t.eq(request2.headers.get("x-request-id"), null);
t.eq(request2.headers.get("x-test"), "42");
});
t.test("construct with request and override body", async (t) => {
const request1 = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
body: "I work out",
headers: {
"Content-Type": "text/plain",
},
});
const request2 = new Request(request1, {
body: '{"wiggles": 5}',
headers: { "Content-Type": "application/json" },
});
const body = await request2.json();
t.eq(body.wiggles, 5);
t.eq(request2.headers.get("content-type"), "application/json");
});
t.test("construct with used request body", async (t) => {
const request1 = new Request("https://fetch.spec.whatwg.org/", {
method: "post",
body: "I work out",
});
await request1.text();
t.throws(() => {
new Request(request1);
}, TypeError);
});
t.test("GET should not have implicit Content-Type", (t) => {
const req = new Request("https://fetch.spec.whatwg.org/");
t.eq(req.headers.get("content-type"), null);
});
t.test(
"POST with blank body should not have implicit Content-Type",
(t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
});
t.eq(req.headers.get("content-type"), null);
}
);
t.test("construct with string body sets Content-Type header", (t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
body: "I work out",
});
t.equal(req.headers.get("content-type"), "text/plain;charset=UTF-8");
});
t.test(
"construct with Blob body and type sets Content-Type header",
(t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
body: new Blob(["test"], { type: "image/png" }),
});
t.eq(req.headers.get("content-type"), "image/png");
}
);
t.test("construct with body and explicit header uses header", (t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
headers: { "Content-Type": "image/png" },
body: "I work out",
});
t.eq(req.headers.get("content-type"), "image/png");
});
t.test("construct with Blob body and explicit Content-Type header", (t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
headers: { "Content-Type": "image/png" },
body: new Blob(["test"], { type: "text/plain" }),
});
t.eq(req.headers.get("content-type"), "image/png");
});
t.test(
"construct with URLSearchParams body sets Content-Type header",
(t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
body: new URLSearchParams("a=1&b=2"),
});
t.eq(
req.headers.get("content-type"),
"application/x-www-form-urlencoded;charset=UTF-8"
);
}
);
t.test(
"construct with URLSearchParams body and explicit Content-Type header",
(t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
method: "post",
headers: { "Content-Type": "image/png" },
body: new URLSearchParams("a=1&b=2"),
});
t.eq(req.headers.get("content-type"), "image/png");
}
);
t.test("construct with unsupported body type", async (t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
body: {},
});
t.eq(req.headers.get("content-type"), "text/plain;charset=UTF-8");
const body = await req.text();
t.eq(body, "[object Object]");
});
t.test("construct with null body", async (t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
});
t.is(req.headers.get("content-type"), null);
const body = await req.text();
t.eq(body, "");
});
t.test("clone GET request", (t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
headers: { "content-type": "text/plain" },
});
const clone = req.clone();
t.eq(clone.url, req.url);
t.eq(clone.method, "GET");
t.eq(clone.headers.get("content-type"), "text/plain");
t.isNot(clone.headers, req.headers);
t.notOk(req.bodyUsed);
});
t.test("clone POST request", async (t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
headers: { "content-type": "text/plain" },
body: "I work out",
});
const clone = req.clone();
t.eq(clone.method, "POST");
t.eq(clone.headers.get("content-type"), "text/plain");
t.isNot(clone.headers, req.headers);
t.notOk(req.bodyUsed);
const bodies = await Promise.all([clone.text(), req.text()]);
t.eq(bodies, ["I work out", "I work out"]);
});
t.test("clone with used request body", async (t) => {
const req = new Request("https://fetch.spec.whatwg.org/", {
method: "POST",
body: "I work out",
});
await req.text();
t.throws(() => {
req.clone();
}, TypeError);
});
t.test("credentials defaults to same-origin", (t) => {
const req = new Request("");
t.eq(req.credentials, "same-origin");
});
t.test("credentials is overridable", (t) => {
const req = new Request("", { credentials: "omit" });
t.eq(req.credentials, "omit");
});
t.test("GET with body throws TypeError", (t) => {
t.throws(() => {
new Request("", { method: "GET", body: "invalid" });
}, TypeError);
});
t.test("HEAD with body throws TypeError", (t) => {
t.throws(() => {
new Request("", { method: "HEAD", body: "invalid" });
}, TypeError);
});
t.test("consume request body as text when input is text", async (t) => {
const text = "Hello world!";
const req = new Request("", { method: "POST", body: text });
t.eq(await req.text(), text);
});
t.test("consume request body as Blob when input is text", async (t) => {
const text = "Hello world!";
const req = new Request("", { method: "POST", body: text });
const blob = await req.blob();
t.eq(await createBlobReader(blob).readAsText(), text);
});
// TODO: Test fails while React Native does not implement FileReader.readAsArrayBuffer
t.skip(
"consume request body as ArrayBuffer when input is text",
async (t) => {
const text = "Hello world!";
const req = new Request("", { method: "POST", body: text });
const arrayBuffer = await req.arrayBuffer();
t.eq(readArrayBufferAsText(arrayBuffer), text);
}
);
t.test(
"consume request body as text when input is ArrayBuffer",
async (t) => {
const array = createTypedArrayFromText("Hello world!");
const req = new Request("", { method: "POST", body: array.buffer });
t.eq(await req.text(), "Hello world!");
}
);
t.test(
"consume request body as text when input is ArrayBufferView",
async (t) => {
const array = createTypedArrayFromText("Hello world!");
const req = new Request("", { method: "POST", body: array });
t.eq(await req.text(), "Hello world!");
}
);
// React Native does not support Blob construction from ArrayBuffer or ArrayBufferView
t.skip(
"consume request body as Blob when input is ArrayBuffer",
async (t) => {
const array = createTypedArrayFromText("Hello world!");
const req = new Request("", { method: "POST", body: array.buffer });
const blob = await req.blob();
t.eq(await createBlobReader(blob).readAsText(), "Hello world!");
}
);
// React Native does not support Blob construction from ArrayBuffer or ArrayBufferView
t.skip(
"consume request body as Blob when input is ArrayBufferView",
async (t) => {
const array = createTypedArrayFromText("Hello world!");
const req = new Request("", { method: "POST", body: array });
const blob = await req.blob();
t.eq(await createBlobReader(blob).readAsText(), "Hello world!");
}
);
t.test(
"consume request body as ArrayBuffer when input is ArrayBuffer",
async (t) => {
const array = createTypedArrayFromText("Hello world!");
const req = new Request("", { method: "POST", body: array });
const text = new TextDecoder().decode(await req.arrayBuffer());
t.eq(text, "Hello world!");
}
);
t.test(
"consume request body as ArrayBuffer when input is ArrayBufferView",
async (t) => {
const array = createTypedArrayFromText("Hello world!");
const req = new Request("", { method: "POST", body: array });
const text = new TextDecoder().decode(await req.arrayBuffer());
t.eq(text, "Hello world!");
}
);
t.test("cache-busting query parameter", (t) => {
const originalDateNow = Date.now;
global.Date.now = () => 12345;
t.test("should not append current time for POST", (t) => {
const req = new Request("https://reactnative.dev/", {
cache: "no-cache",
method: "POST",
});
const searchParams = new URL(req.url).searchParams;
t.notOk(searchParams.has("_"));
});
t.test("should not append current time for PUT", (t) => {
const req = new Request("https://reactnative.dev/", {
cache: "no-cache",
method: "PUT",
});
const searchParams = new URL(req.url).searchParams;
t.notOk(searchParams.has("_"));
});
t.test("should not append current time for PATCH", (t) => {
const req = new Request("https://reactnative.dev/", {
cache: "no-cache",
method: "PATCH",
});
const searchParams = new URL(req.url).searchParams;
t.notOk(searchParams.has("_"));
});
t.test("should append current time for GET", (t) => {
const req = new Request("https://reactnative.dev/", {
cache: "no-cache",
method: "GET",
});
const searchParams = new URL(req.url).searchParams;
t.ok(searchParams.has("_"));
t.eq(searchParams.get("_"), `${Date.now()}`);
});
t.test("should append current time for HEAD", (t) => {
const req = new Request("https://reactnative.dev/", {
cache: "no-cache",
method: "HEAD",
});
const searchParams = new URL(req.url).searchParams;
t.ok(searchParams.has("_"));
t.eq(searchParams.get("_"), "12345");
});
t.test("should replace existing value", (t) => {
const req = new Request("https://reactnative.dev/?_=67890", {
cache: "no-cache",
method: "GET",
});
const searchParams = new URL(req.url).searchParams;
t.ok(searchParams.has("_"));
t.eq(searchParams.get("_"), "12345");
});
t.test("should append current time with no-store option too", (t) => {
const req = new Request("https://reactnative.dev/", {
cache: "no-store",
method: "GET",
});
const searchParams = new URL(req.url).searchParams;
t.ok(searchParams.has("_"));
t.eq(searchParams.get("_"), "12345");
});
t.test("should replace existing value with no-store option", (t) => {
const req = new Request("https://reactnative.dev/?_=67890", {
cache: "no-store",
method: "GET",
});
const searchParams = new URL(req.url).searchParams;
t.ok(searchParams.has("_"));
t.eq(searchParams.get("_"), "12345");
});
global.Date.now = originalDateNow;
});
});
test("response", (t) => {
t.test("default status is 200", (t) => {
const res = new Response();
t.eq(res.status, 200);
t.eq(res.statusText, "");
t.ok(res.ok);
});
t.test(
"default status is 200 when an explicit undefined status is passed",
(t) => {
const res = new Response("", { status: undefined });
t.eq(res.status, 200);
t.eq(res.statusText, "");
t.ok(res.ok);
}
);
t.test("should throw when called without constructor", (t) => {
t.throws(() => {
Response('{"foo":"bar"}', {
headers: { "content-type": "application/json" },
});
});
});
t.test("creates headers object from raw headers", async (t) => {
const res = new Response('{"foo":"bar"}', {
headers: { "content-type": "application/json" },
});
const json = await res.json();
t.ok(res.headers instanceof Headers);
t.eq(json.foo, "bar");
});
t.test("always creates a new headers instance", (t) => {
const headers = new Headers({ "x-hello": "world" });
const res = new Response("", { headers });
t.eq(res.headers.get("x-hello"), "world");
t.isNot(res.headers, headers);
});
t.test("clone text response", async (t) => {
const res = new Response('{"foo":"bar"}', {
headers: { "content-type": "application/json" },
});
const clone = res.clone();
t.isNot(clone.headers, res.headers, "headers were cloned");
t.eq(clone.headers.get("content-type"), "application/json");
const jsons = await Promise.all([clone.json(), res.json()]);
t.eq(
jsons[0],
jsons[1],
"json of cloned object is the same as original"
);
});
t.test("error creates error Response", (t) => {
const res = Response.error();
t.ok(res instanceof Response);
t.eq(res.status, 0);
t.eq(res.statusText, "");
t.eq(res.type, "error");
});
t.test("redirect creates redirect Response", (t) => {
const res = Response.redirect("https://fetch.spec.whatwg.org/", 301);
t.ok(res instanceof Response);
t.eq(res.status, 301);
t.eq(res.headers.get("Location"), "https://fetch.spec.whatwg.org/");
});
t.test("construct with string body sets Content-Type header", (t) => {
const res = new Response("I work out");
t.eq(res.headers.get("content-type"), "text/plain;charset=UTF-8");
});
t.test(
"construct with Blob body and type sets Content-Type header",
(t) => {
const res = new Response(
new Blob(["test"], { type: "text/plain" })
);
t.eq(res.headers.get("content-type"), "text/plain");
}
);
t.test("construct with body and explicit header uses header", (t) => {
const res = new Response("I work out", {
headers: {
"Content-Type": "text/plain",
},
});
t.eq(res.headers.get("content-type"), "text/plain");
});
t.test("init object as first argument", async (t) => {
const res = new Response({
status: 201,
headers: {
"Content-Type": "text/html",
},
});
t.eq(res.status, 200);
t.eq(res.headers.get("content-type"), "text/plain;charset=UTF-8");
const text = await res.text();
t.eq(text, "[object Object]");
});
t.test("null as first argument", async (t) => {
const res = new Response(null);
t.is(res.headers.get("content-type"), null);
const text = await res.text();
t.eq(text, "");
});
t.test("consume response body as text when input is text", async (t) => {
const text = "Hello world!";
const req = new Response(text);
t.eq(await req.text(), text);
});
t.test("consume response body as Blob when input is text", async (t) => {
const text = "Hello world!";
const res = new Response(text);
const blob = await res.blob();
t.eq(await createBlobReader(blob).readAsText(), text);
});
// TODO: Test fails while React Native does not implement FileReader.readAsArrayBuffer
t.skip(
"consume request body as ArrayBuffer when input is text",
async (t) => {
const text = "Hello world!";
const res = new Response(text);
const arrayBuffer = await res.arrayBuffer();
t.eq(readArrayBufferAsText(arrayBuffer), text);
}
);
t.test(
"consume request body as text when input is ArrayBuffer",
async (t) => {
const array = createTypedArrayFromText("Hello world!");
const res = new Response(array.buffer);
t.eq(await res.text(), "Hello world!");
}
);
t.test(
"consume request body as text when input is ArrayBufferView",
async (t) => {
const array = createTypedArrayFromText("Hello world!");
const res = new Response(array);
t.eq(await res.text(), "Hello world!");
}
);
// React Native does not support Blob construction from ArrayBuffer or ArrayBufferView
t.skip(
"consume request body as Blob when input is ArrayBuffer",
async (t) => {
const array = createTypedArrayFromText("Hello world!").buffer;
const res = new Response(array.buffer);
const blob = await res.blob();
t.eq(await createBlobReader(blob).readAsText(), "Hello world!");
}
);
// React Native does not support Blob construction from ArrayBuffer or ArrayBufferView
t.skip(
"consume request body as Blob when input is ArrayBufferView",
async (t) => {
const array = createTypedArrayFromText("Hello world!");
const res = new Response("", { method: "POST", body: array });
const blob = await res.blob();
t.eq(await createBlobReader(blob).readAsText(), "Hello world!");
}
);
t.test(
"consume request body as ArrayBuffer when input is ArrayBuffer",
async (t) => {
const array = createTypedArrayFromText("Hello world!");
const res = new Response(array);