Debian Codegraph @

test/lib/fetch-mock.js

raw symbols SCIP
1 /**
2 * Mock implementation of the Fetch API for testing
3 */
4
5 class MockResponse {
6 constructor(body, init = {}) {
7 this.body = body;
8 this.status = init.status || 200;
9 this.ok = this.status >= 200 && this.status < 300;
10 this.statusText = init.statusText || '';
11 this.headers = new Map(Object.entries(init.headers || {}));
12 this.url = init.url || '';
13 this.type = init.type || 'basic';
14 }
15
16 async json() {
17 if (typeof this.body === 'string') {
18 return JSON.parse(this.body);
19 }
20 return this.body;
21 }
22
23 async text() {
24 if (typeof this.body === 'string') {
25 return this.body;
26 }
27 return JSON.stringify(this.body);
28 }
29
30 async blob() {
31 return new Blob([await this.text()]);
32 }
33
34 async arrayBuffer() {
35 const text = await this.text();
36 const encoder = new TextEncoder();
37 return encoder.encode(text).buffer;
38 }
39
40 clone() {
41 return new MockResponse(this.body, {
42 status: this.status,
43 statusText: this.statusText,
44 headers: Object.fromEntries(this.headers),
45 url: this.url,
46 type: this.type
47 });
48 }
49 }
50
51 class FetchMock {
52 constructor() {
53 this.reset();
54 }
55
56 reset() {
57 // Abort all pending requests before clearing
58 if (this.pendingRequests) {
59 this.pendingRequests.forEach(({ controller }) => {
60 if (controller && !controller.signal.aborted) {
61 controller.abort();
62 }
63 });
64 }
65 this.calls = [];
66 this.responses = [];
67 this.pendingRequests = [];
68 }
69
70 // Record a fetch call
71 recordCall(url, options) {
72 this.calls.push({ url, request: options });
73 }
74
75 // Get all recorded calls
76 getCalls() {
77 return this.calls;
78 }
79
80 // Get the last call
81 getLastCall() {
82 return this.calls[this.calls.length - 1];
83 }
84
85 // Mock a response for a specific URL pattern
86 mockResponse(method, urlPattern, response, options = {}) {
87 let upperCasedMethod = method.toUpperCase();
88 if (['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].indexOf(upperCasedMethod) < 0) {
89 throw Error("Invalid HTTP method: " + method)
90 }
91 if (typeof response === 'string') {
92 let str = response;
93 response = new MockResponse(str, options);
94 }
95 this.responses.push({
96 method: upperCasedMethod,
97 urlPattern: typeof urlPattern === 'string' ? new RegExp(urlPattern) : urlPattern,
98 response,
99 request: options,
100 once: options.once || false,
101 used: false
102 });
103 }
104
105 // Mock a successful JSON response
106 mockJsonResponse(method, urlPattern, data, status = 200) {
107 this.mockResponse(method, urlPattern, new MockResponse(data, {
108 status,
109 headers: { 'Content-Type': 'application/json' }
110 }));
111 }
112
113 // Mock an error response
114 mockErrorResponse(method, urlPattern, status = 500, message = 'Server Error') {
115 this.mockResponse(method, urlPattern, new MockResponse({ error: message }, { status }));
116 }
117
118 // Mock a network error
119 mockNetworkError(method, urlPattern, error = new Error('Network Error')) {
120 this.mockResponse(method, urlPattern, Promise.reject(error));
121 }
122
123 // Mock a network failure (simpler alias)
124 mockFailure(method, urlPattern, message = 'Network failure') {
125 this.mockNetworkError(method, urlPattern, new Error(message));
126 }
127
128 // Mock sequential responses that don't resolve until explicitly released
129 // Returns an object with next() to release requests one at a time
130 mockSequentialResponses(method, urlPattern, response, options = {}) {
131 const pendingQueue = []; // Requests waiting to be resolved
132 const waiters = []; // next() calls waiting for requests
133
134 // Register a response function that holds requests
135 this.mockResponse(method, urlPattern, () => {
136 return new Promise(resolve => {
137 const responseBody = typeof response === 'string'
138 ? new MockResponse(response, options)
139 : response;
140
141 // If there's already a waiter, resolve immediately
142 if (waiters.length > 0) {
143 const waiter = waiters.shift();
144 resolve(responseBody);
145 // Wait for htmx to finish processing, then resolve waiter
146 setTimeout(() => waiter(), 0);
147 } else {
148 // Queue this request to be released later
149 pendingQueue.push({ resolve, responseBody });
150 }
151 });
152 });
153
154 return {
155 // Release next pending request and wait for htmx to finish processing
156 next() {
157 return new Promise(resolve => {
158 if (pendingQueue.length > 0) {
159 // Request already waiting, release it
160 const item = pendingQueue.shift();
161 item.resolve(item.responseBody);
162 // Give htmx time to process the response
163 setTimeout(resolve, 0);
164 } else {
165 // No request yet, wait for one to arrive
166 waiters.push(resolve);
167 }
168 });
169 },
170 // Get count of pending requests
171 get pendingCount() {
172 return pendingQueue.length;
173 }
174 };
175 }
176
177 // Find matching response
178 findResponse(method, url) {
179 for (let i = this.responses.length - 1; i >= 0; i--) {
180 const mock = this.responses[i];
181 if (mock.method === method && mock.urlPattern.test(url)) {
182 if (mock.once) {
183 if (!mock.used) {
184 mock.used = true;
185 return typeof mock.response === 'function' ? mock.response() : mock.response;
186 }
187 } else {
188 return typeof mock.response === 'function' ? mock.response() : mock.response;
189 }
190 }
191 }
192 console.error("no response configured for ", url, " available responses: ", this.responses);
193 return "NO RESPONSE CONFIGURED FOR " + url;
194 }
195
196 // Wait for all pending requests to complete
197 async waitForRequests() {
198 if (this.pendingRequests.length === 0) {
199 return Promise.resolve();
200 }
201 await Promise.all(this.pendingRequests.map(req => req.promise));
202 }
203
204 // The actual fetch mock function
205 fetch(url, options = {}) {
206 this.recordCall(url, options);
207 options.method = options.method.toUpperCase()
208 const response = this.findResponse(options.method, url);
209
210 // Create an AbortController for this request
211 const controller = new AbortController();
212
213 // Create a tracking object for this request
214 const pendingRequest = { controller, promise: null };
215
216 // Create a promise to track this request
217 const requestPromise = new Promise((resolve, reject) => {
218 // Check if already aborted
219 if (controller.signal.aborted) {
220 reject(new DOMException('The operation was aborted', 'AbortError'));
221 return;
222 }
223
224 // Listen for abort
225 controller.signal.addEventListener('abort', () => {
226 reject(new DOMException('The operation was aborted', 'AbortError'));
227 });
228
229 // Process the response
230 Promise.resolve(response)
231 .then(result => {
232 if (typeof result === 'string') result = new MockResponse(result);
233 if (!controller.signal.aborted) {
234 resolve(result);
235 }
236 })
237 .catch(error => {
238 if (!controller.signal.aborted) {
239 reject(error);
240 }
241 });
242 })
243 .finally(() => {
244 // Remove from pending requests when done
245 const index = this.pendingRequests.indexOf(pendingRequest);
246 if (index > -1) {
247 this.pendingRequests.splice(index, 1);
248 }
249 });
250
251 // Store the promise in the tracking object
252 pendingRequest.promise = requestPromise;
253
254 // Track this pending request
255 this.pendingRequests.push(pendingRequest);
256
257 return requestPromise;
258 }
259 }
260
261 // Create a global instance
262 const fetchMock = new FetchMock();
263
264 // Install the mock globally
265 function installFetchMock() {
266 globalThis.fetch = fetchMock.fetch.bind(fetchMock);
267 }
268
269 // Uninstall the mock and restore original fetch
270 let originalFetch;
271 function uninstallFetchMock() {
272 if (originalFetch) {
273 globalThis.fetch = originalFetch;
274 }
275 }
276
277 // Save original fetch before installing
278 if (typeof globalThis.fetch !== 'undefined') {
279 originalFetch = globalThis.fetch;
280 }