-
Notifications
You must be signed in to change notification settings - Fork 202
Expand file tree
/
Copy pathindex.test.mjs
More file actions
104 lines (90 loc) · 2.58 KB
/
index.test.mjs
File metadata and controls
104 lines (90 loc) · 2.58 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
import fetch from "../src/index.mjs";
import fetchDist from "..";
describe("unfetch", () => {
it("should be a function", () => {
expect(fetch).toEqual(expect.any(Function));
});
it("should be compiled correctly", () => {
expect(fetchDist).toEqual(expect.any(Function));
expect(fetchDist).toHaveLength(2);
});
describe("fetch()", () => {
let xhr;
beforeEach(() => {
xhr = {
setRequestHeader: jest.fn(),
getAllResponseHeaders: jest
.fn()
.mockReturnValue(
"X-Foo: bar\r\nX-Foo: baz\r\nX-Bar: bar, baz\r\nx-test: \r\nX-Baz: bar, baz\r\ndate: 18:23:22"
),
getResponseHeader: jest.fn().mockReturnValue("bar, baz"),
open: jest.fn(),
send: jest.fn(),
status: 200,
statusText: "OK",
responseText: '{"a":"b"}',
responseURL: "/foo?redirect",
};
global.XMLHttpRequest = jest.fn(() => xhr);
});
afterEach(() => {
delete global.XMLHttpRequest;
});
it("sanity test", () => {
let p = fetch("/foo", { headers: { a: "b" } })
.then((r) => {
expect(r).toMatchObject({
text: expect.any(Function),
json: expect.any(Function),
blob: expect.any(Function),
clone: expect.any(Function),
headers: expect.any(Object),
});
expect(r.clone()).not.toBe(r);
expect(r.clone().url).toEqual("/foo?redirect");
expect(r.headers.get).toEqual(expect.any(Function));
expect(r.headers.get("x-foo")).toEqual("bar, baz");
expect(r.headers.keys()).toEqual([
"x-foo",
"x-bar",
"x-test",
"x-baz",
"date",
]);
return r.json();
})
.then((data) => {
expect(data).toEqual({ a: "b" });
expect(xhr.setRequestHeader).toHaveBeenCalledTimes(1);
expect(xhr.setRequestHeader).toHaveBeenCalledWith("a", "b");
expect(xhr.open).toHaveBeenCalledTimes(1);
expect(xhr.open).toHaveBeenCalledWith("get", "/foo", true);
expect(xhr.send).toHaveBeenCalledTimes(1);
expect(xhr.send).toHaveBeenCalledWith(null);
});
expect(xhr.onload).toEqual(expect.any(Function));
expect(xhr.onerror).toEqual(expect.any(Function));
xhr.onload();
return p;
});
it("handles empty header values", () => {
xhr.getAllResponseHeaders = jest
.fn()
.mockReturnValue("Server: \nX-Foo:baz");
const headers = {
server: "",
"x-foo": "baz",
};
xhr.getResponseHeader = jest.fn(
(header) => headers[header.toLowerCase()] ?? null
);
let p = fetch("/foo").then((r) => {
expect(r.headers.get("server")).toEqual("");
expect(r.headers.get("X-foo")).toEqual("baz");
});
xhr.onload();
return p;
});
});
});