-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
314 lines (265 loc) · 7.21 KB
/
Copy pathindex.ts
File metadata and controls
314 lines (265 loc) · 7.21 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
import { afterAll, beforeAll, expect, spyOn } from "bun:test";
const DEFAULT_METHOD = "GET";
type HttpMethod =
| "GET"
| "POST"
| "PUT"
| "DELETE"
| "PATCH"
| "HEAD"
| "OPTIONS";
interface MockResponse<T = unknown> {
data?: T;
status?: number;
headers?: Record<string, string>;
statusText?: string;
}
/**
* Options for configuring a mocked response.
*/
export interface MockOpts<T = unknown> extends MockResponse<T> {
/**
* When true, removes this mock after the first matching request.
*/
once?: boolean;
}
/**
* Accepted URL input for registering a mock.
* Use an absolute URL or a path that starts with `/`.
*/
export type UrlOrPath = `https://${string}` | `http://${string}` | `/${string}`;
function getKey({ method, url }: { method: HttpMethod; url: string }) {
return `[${method}] ${url}`;
}
function joinBaseUrl(baseUrl: string, path: string) {
if (!baseUrl) {
return path;
}
const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
return `${normalizedBaseUrl}${path}`;
}
export interface FetchMockOpts {
/**
* Optional base URL prepended to path-style mock URLs (for example `/users`).
*/
baseUrl?: string;
}
type ValidationError = {
message: string;
url?: string;
method?: HttpMethod;
};
class FetchMock {
readonly baseUrl: string;
readonly mocks = new Map<string, { isUsed: boolean } & MockOpts<unknown>>();
private mockQueue = new Map<
string,
Array<{ isUsed: boolean } & MockOpts<unknown>>
>();
constructor(opts: FetchMockOpts) {
this.baseUrl = opts.baseUrl ?? "";
}
private validateUrl(url: UrlOrPath): ValidationError | null {
if (!url || typeof url !== "string") {
return { message: "URL must be a non-empty string" };
}
if (
!url.startsWith("http://") &&
!url.startsWith("https://") &&
!url.startsWith("/")
) {
return { message: "URL must start with http://, https://, or /" };
}
return null;
}
private validateMethod(method: string): method is HttpMethod {
const validMethods: HttpMethod[] = [
"GET",
"POST",
"PUT",
"DELETE",
"PATCH",
"HEAD",
"OPTIONS",
];
return validMethods.includes(method as HttpMethod);
}
/**
* Clears all registered mocks and queued follow-up mocks.
*/
reset(this: FetchMock) {
this.mocks.clear();
this.mockQueue.clear();
return this;
}
/**
* Registers a mock for a `GET` request.
*/
get<T>(this: FetchMock, url: UrlOrPath, opts?: MockOpts<T>) {
return this.#mockRequest("GET", url, opts);
}
/**
* Registers a mock for a `POST` request.
*/
post<T>(this: FetchMock, url: UrlOrPath, opts?: MockOpts<T>) {
return this.#mockRequest("POST", url, opts);
}
/**
* Registers a mock for a `PUT` request.
*/
put<T>(this: FetchMock, url: UrlOrPath, opts?: MockOpts<T>) {
return this.#mockRequest("PUT", url, opts);
}
/**
* Registers a mock for a `DELETE` request.
*/
delete<T>(this: FetchMock, url: UrlOrPath, opts?: MockOpts<T>) {
return this.#mockRequest("DELETE", url, opts);
}
/**
* Registers a mock for a `PATCH` request.
*/
patch<T>(this: FetchMock, url: UrlOrPath, opts?: MockOpts<T>) {
return this.#mockRequest("PATCH", url, opts);
}
/**
* Registers a mock for a `HEAD` request.
*/
head<T>(this: FetchMock, url: UrlOrPath, opts?: MockOpts<T>) {
return this.#mockRequest("HEAD", url, opts);
}
/**
* Registers a mock for an `OPTIONS` request.
*/
options<T>(this: FetchMock, url: UrlOrPath, opts?: MockOpts<T>) {
return this.#mockRequest("OPTIONS", url, opts);
}
/**
* Asserts that every configured mock has been used at least once.
*/
assertAllMocksUsed(this: FetchMock) {
for (const [key, opts] of this.mocks.entries()) {
expect(opts.isUsed, `Fetch mock ${key} was not used`).toBe(true);
}
for (const [key, queue] of this.mockQueue.entries()) {
for (const opts of queue) {
expect(opts.isUsed, `Fetch mock ${key} was not used`).toBe(true);
}
}
}
/**
* Internal fetch implementation used by the `globalThis.fetch` spy.
*
* @throws If the request method is unsupported or no matching mock exists.
*/
async fetchMock(
this: FetchMock,
url: string,
init?: RequestInit,
): Promise<Response> {
const methodStr = (init?.method ?? DEFAULT_METHOD).toUpperCase();
if (!this.validateMethod(methodStr)) {
throw new Error(
`Unsupported HTTP method: ${methodStr}. Supported methods: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS`,
);
}
const method = methodStr as HttpMethod;
const key = getKey({ method, url });
const opts = this.mocks.get(key);
if (!opts) {
const allMocks = [
...Array.from(this.mocks.keys()),
...Array.from(this.mockQueue.keys()),
];
const availableMocks = allMocks.join(", ");
throw new Error(
`No mock found for ${key}${availableMocks ? `. Available mocks: ${availableMocks}` : ""}`,
);
}
const { once, data, status = 200, headers = {}, statusText = "OK" } = opts;
opts.isUsed = true;
if (once) {
this.mocks.delete(key);
const queue = this.mockQueue.get(key);
if (queue && queue.length > 0) {
const nextMock = queue.shift();
if (nextMock) {
this.mocks.set(key, nextMock);
}
if (queue.length === 0) {
this.mockQueue.delete(key);
}
}
}
if (method === "HEAD") {
return new Response(null, { status, headers, statusText });
}
if (data === undefined) {
return new Response(null, { status, headers, statusText });
}
if (typeof data === "string") {
return new Response(data, {
status,
headers: { "Content-Type": "text/plain", ...headers },
statusText,
});
}
return Response.json(data, { status, headers, statusText });
}
/**
* Adds a mock entry for an HTTP method + URL pair.
* If one already exists for the same key, queues this mock to be used next.
*/
#mockRequest<T>(method: HttpMethod, url: UrlOrPath, opts?: MockOpts<T>) {
const urlError = this.validateUrl(url);
if (urlError) {
throw new Error(`Invalid URL for ${method} mock: ${urlError.message}`);
}
const fullUrl = url.startsWith("/") ? joinBaseUrl(this.baseUrl, url) : url;
const key = getKey({ method, url: fullUrl });
const mockData = {
...opts,
isUsed: false,
};
if (this.mocks.has(key)) {
const queue = this.mockQueue.get(key) || [];
queue.push(mockData);
this.mockQueue.set(key, queue);
} else {
this.mocks.set(key, mockData);
}
return this;
}
}
/**
* Creates a fetch mock instance and wires it into Bun's test lifecycle.
*
* `fetch` is mocked immediately and restored in `afterAll`.
* Call this at module scope or inside `describe(...)`, not inside `test(...)`.
*/
export function useFetchMock(opts: FetchMockOpts = {}) {
const mock = new FetchMock(opts);
const spyFetch = spyOn(globalThis, "fetch");
spyFetch.mockImplementation(
(mock.fetchMock as unknown as typeof fetch).bind(mock),
);
try {
beforeAll(() => {
if (!spyFetch.mock) {
spyFetch.mockImplementation(
(mock.fetchMock as unknown as typeof fetch).bind(mock),
);
}
});
afterAll(() => {
spyFetch.mockRestore();
});
} catch (error) {
spyFetch.mockRestore();
const detail = error instanceof Error ? error.message : String(error);
throw new Error(
`useFetchMock() must be called at module scope or inside describe(), not inside test(). ${detail}`,
);
}
return mock;
}