-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmock-utils.ts
190 lines (167 loc) · 4.84 KB
/
mock-utils.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
import { MockNotMatchedError } from "./mock-fetch.error.ts";
import { MockMatcher, MockRequest, RequestKey } from "./mock-fetch.type.ts";
export function matchValue(
matcher: MockMatcher,
value: string,
) {
if (typeof matcher === "string") {
return matcher === value;
}
if (matcher instanceof RegExp) {
return matcher.test(value);
}
return matcher(value) === true;
}
/**
* As per RFC 3986, clients are not supposed to send URI
* fragments to servers when they retrieve a document. Therefore,
* we strip these out.
*/
export function stripURIFragments(rawURL: string): string {
const url = new URL(rawURL);
return url.href.replace(url.hash, "");
}
export function safeURL(rawURL: string): string {
const urlSegments = rawURL.split("?");
if (urlSegments.length !== 2) {
return stripURIFragments(rawURL);
}
const qp = new URLSearchParams(urlSegments.pop());
qp.sort();
return stripURIFragments([...urlSegments, qp.toString()].join("?"));
}
export function getResourceMethod(
input: string | Request | URL,
init: RequestInit | undefined,
): string {
if (input instanceof Request) {
return input.method;
}
return init?.method || "GET";
}
export function getResourceURL(input: string | Request | URL): URL {
if (typeof input === "string") {
return new URL(input);
}
if (input instanceof URL) {
return input;
}
return new URL(input.url);
}
export function getResourceHeaders(
input: URL | Request | string,
init?: RequestInit,
): Headers {
if (input instanceof Request) {
return input.headers;
}
if (init?.headers) {
return new Headers(init.headers);
}
return new Headers();
}
export async function getResourceBody(
input: URL | Request | string,
init?: RequestInit,
): Promise<string | undefined> {
if (input instanceof Request) {
return await input.text();
}
if (init?.body) {
if (init.body instanceof FormData) {
return JSON.stringify([...init.body.entries()]);
}
return init.body.toString();
}
}
export async function buildKey(
input: URL | Request | string,
init?: RequestInit,
): Promise<RequestKey> {
const url = getResourceURL(input);
return {
url,
method: getResourceMethod(input, init),
body: await getResourceBody(input, init),
headers: getResourceHeaders(input, init),
query: url.searchParams,
};
}
export function isMockMatcher(input: unknown): input is MockMatcher {
return typeof input === "string" || typeof input === "function" ||
input instanceof RegExp;
}
export function matchHeaders(
mockRequest: MockRequest,
headers: Headers,
) {
let mockHeaderMatchers: [string, MockMatcher][] = [];
if (mockRequest.request.input instanceof Request) {
mockHeaderMatchers = [...mockRequest.request.input.headers.entries()];
} else {
const initHeaders = mockRequest.request.init?.headers;
if (initHeaders instanceof Headers) {
mockHeaderMatchers = [...initHeaders.entries()];
} else if (Array.isArray(initHeaders)) {
mockHeaderMatchers = [...initHeaders] as [string, MockMatcher][];
} else if (typeof initHeaders === "function") {
return initHeaders(headers);
} else if (initHeaders) {
mockHeaderMatchers = [...Object.entries(initHeaders)];
}
}
for (const [headerName, headerMatcher] of mockHeaderMatchers) {
const header = headers.get(headerName);
if (header === null || !matchValue(headerMatcher, header)) {
return false;
}
}
return true;
}
export function getMockRequest(
mockRequests: MockRequest[],
key: RequestKey,
): MockRequest {
// Match URL
let matchedMockRequests = mockRequests
.filter(({ consumed }) => !consumed)
.filter(({ request }) => matchValue(request.url, key.url.href));
if (matchedMockRequests.length === 0) {
throw new MockNotMatchedError(
`Mock Request not matched for URL '${key.url}'`,
);
}
// Match method
matchedMockRequests = matchedMockRequests.filter(({ request }) =>
matchValue(request.method, key.method)
);
if (matchedMockRequests.length === 0) {
throw new MockNotMatchedError(
`Mock Request not matched for method '${key.method}'`,
);
}
// Match body
matchedMockRequests = matchedMockRequests.filter(({ request }) =>
typeof request.body !== "undefined"
? matchValue(request.body, key.body ?? "")
: true
);
if (matchedMockRequests.length === 0) {
throw new MockNotMatchedError(
`Mock Request not matched for body '${key.body}'`,
);
}
// Match headers
matchedMockRequests = matchedMockRequests.filter((mockRequest) =>
matchHeaders(mockRequest, key.headers)
);
if (matchedMockRequests.length === 0) {
throw new MockNotMatchedError(
`Mock Request not matched for headers '${
JSON.stringify([...key.headers.entries()])
}'`,
);
}
// Only take the first matched request
return matchedMockRequests[0];
}