-
Notifications
You must be signed in to change notification settings - Fork 42
/
mock-axios.ts
405 lines (342 loc) · 12.1 KB
/
mock-axios.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
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
/**
* TypeScript version of Axios mock for unit testing with [Jest](https://facebook.github.io/jest/).
* This file is based on https://gist.github.com/tux4/36006a1859323f779ab0
*
* @author knee-cola <[email protected]>
* @license @license MIT License, http://www.opensource.org/licenses/MIT
*/
import {jest} from '@jest/globals';
import { SynchronousPromise, UnresolvedSynchronousPromise } from "synchronous-promise";
import Cancel from "./cancel/Cancel";
import CancelToken from "./cancel/CancelToken";
import {
AxiosMockQueueItem,
AxiosMockRequestCriteria,
AxiosMockType,
HttpResponse,
InterceptorsStack,
RequestHandler,
} from "./mock-axios-types";
/** a FIFO queue of pending request */
const _pending_requests: AxiosMockQueueItem[] = [];
const _responseInterceptors: InterceptorsStack[] = [];
const _requestInterceptors: InterceptorsStack[] = [];
let _requestHandler: RequestHandler;
const processInterceptors = (data: any, stack: InterceptorsStack[], type: keyof InterceptorsStack) => {
return stack.map(({[type]: interceptor}) => interceptor)
.filter((interceptor) => !!interceptor)
.reduce((_result, next) => {
return next(_result);
}, data);
}
const _newReq: (config?: any) => UnresolvedSynchronousPromise<any> = (config: any = {}, actualConfig: any = {}) => {
if(typeof config === 'string') {
// Allow for axios('example/url'[, config])
actualConfig.url = config;
config = actualConfig;
}
const method: string = config.method || "get";
const url: string = config.url;
const data: any = config.data;
const promise: UnresolvedSynchronousPromise<any> = SynchronousPromise.unresolved();
if(config.cancelToken) {
config.cancelToken.promise.then((cancel: any) => {
// check if promise is still waiting for an answer
if(_pending_requests.find(x => x.promise === promise)) {
MockAxios.mockError(cancel, promise)
}
})
}
const requestConfig = processInterceptors({
config,
data,
method,
promise,
url
}, _requestInterceptors, 'onFulfilled');
_pending_requests.push(requestConfig);
if (typeof _requestHandler === "function") {
_requestHandler(requestConfig);
}
return promise;
};
const _helperReq = (method: string, url: string, data?: any, config?: any) => {
const conf = data && config ? config : {};
return _newReq({
...conf,
data,
method,
url,
});
};
const _helperReqNoData = (method: string, url: string, config?: any) => {
return _helperReq(method, url, {}, config)
}
const MockAxios: AxiosMockType = (jest.fn(_newReq) as unknown) as AxiosMockType;
// mocking Axios methods
// @ts-ignore
MockAxios.get = jest.fn(_helperReqNoData.bind(null, "get"));
// @ts-ignore
MockAxios.post = jest.fn(_helperReq.bind(null, "post"));
// @ts-ignore
MockAxios.put = jest.fn(_helperReq.bind(null, "put"));
// @ts-ignore
MockAxios.patch = jest.fn(_helperReq.bind(null, "patch"));
// @ts-ignore
MockAxios.delete = jest.fn(_helperReqNoData.bind(null, "delete"));
// @ts-ignore
MockAxios.request = jest.fn(_newReq);
// @ts-ignore
MockAxios.all = jest.fn((values) => Promise.all(values));
// @ts-ignore
MockAxios.head = jest.fn(_helperReqNoData.bind(null, "head"));
// @ts-ignore
MockAxios.options = jest.fn(_helperReqNoData.bind(null, "options"));
// @ts-ignore
MockAxios.create = jest.fn(() => MockAxios);
MockAxios.interceptors = {
request: {
// @ts-ignore
use: jest.fn((onFulfilled, onRejected) => {
return _requestInterceptors.push({ onFulfilled, onRejected })
}),
// @ts-ignore
eject: jest.fn((position: number) => {
_requestInterceptors.splice(position - 1, 1);
}),
// @ts-ignore
clear: jest.fn(() => {
_requestInterceptors.length = 0;
}),
},
response: {
// @ts-ignore
use: jest.fn((onFulfilled, onRejected) => {
return _responseInterceptors.push({onFulfilled, onRejected});
}),
// @ts-ignore
eject: jest.fn((position: number) => {
_responseInterceptors.splice(position - 1, 1);
}),
// @ts-ignore
clear: jest.fn(() => {
_responseInterceptors.length = 0;
}),
},
};
MockAxios.defaults = {
headers: {
common: [],
get: {},
post: {},
delete: {},
put: {},
patch: {},
head: {}
},
};
MockAxios.popPromise = (promise?: SynchronousPromise<any>) => {
if (promise) {
// remove the promise from pending queue
for (let ix = 0; ix < _pending_requests.length; ix++) {
const req: AxiosMockQueueItem = _pending_requests[ix];
if (req.promise === promise) {
_pending_requests.splice(ix, 1);
return req.promise;
}
}
} else {
// take the oldest promise
const req: AxiosMockQueueItem = _pending_requests.shift();
return req ? req.promise : void 0;
}
};
MockAxios.popRequest = (request?: AxiosMockQueueItem) => {
if (request) {
const ix = _pending_requests.indexOf(request);
if (ix === -1) {
return void 0;
}
_pending_requests.splice(ix, 1);
return request;
} else {
return _pending_requests.shift();
}
};
/**
* Removes an item form the queue, based on it's type
* @param queueItem
*/
const popQueueItem = (queueItem: SynchronousPromise<any> | AxiosMockQueueItem = null) => {
// first let's pretend the param is a queue item
const request: AxiosMockQueueItem = MockAxios.popRequest(
queueItem as AxiosMockQueueItem,
);
if (request) {
// IF the request was found
// > set the promise
return request.promise;
} else {
// ELSE maybe the `queueItem` is a promise (legacy mode)
return MockAxios.popPromise(queueItem as UnresolvedSynchronousPromise<any>);
}
};
MockAxios.mockResponse = (
response?: HttpResponse,
queueItem: SynchronousPromise<any> | AxiosMockQueueItem = null,
silentMode: boolean = false,
): void => {
// replacing missing data with default values
response = Object.assign(
{
config: {},
data: {},
headers: {},
status: 200,
statusText: "OK",
},
response,
);
let promise = popQueueItem(queueItem);
if (!promise && !silentMode) {
throw new Error("No request to respond to!");
} else if (!promise) {
return;
}
for (const interceptor of _responseInterceptors) {
promise = promise.then(interceptor.onFulfilled, interceptor.onRejected) as UnresolvedSynchronousPromise<any>;
}
// resolving the Promise with the given response data
promise.resolve(response);
};
MockAxios.mockResponseFor = (
criteria: string | AxiosMockRequestCriteria,
response?: HttpResponse,
silentMode: boolean = false,
): void => {
if (typeof criteria === "string") {
criteria = {url: criteria};
}
const queueItem = MockAxios.getReqMatching(criteria);
if (!queueItem && !silentMode) {
throw new Error("No request to respond to!");
} else if (!queueItem) {
return;
}
MockAxios.mockResponse(response, queueItem, silentMode);
};
MockAxios.mockError = (
error: any = {},
queueItem: SynchronousPromise<any> | AxiosMockQueueItem = null,
silentMode: boolean = false,
) => {
let promise = popQueueItem(queueItem);
if (!promise && !silentMode) {
throw new Error("No request to respond to!");
} else if (!promise) {
return;
}
if (error && typeof error === 'object' && error.isAxiosError === void 0) {
error.isAxiosError = true;
}
for (const interceptor of _responseInterceptors) {
promise = promise.then(interceptor.onFulfilled, interceptor.onRejected) as UnresolvedSynchronousPromise<any>;;
}
// resolving the Promise with the given error
promise.reject(error);
};
MockAxios.isAxiosError = (payload) => (typeof payload === 'object') && (payload.isAxiosError === true);
MockAxios.lastReqGet = () => {
return _pending_requests[_pending_requests.length - 1];
};
MockAxios.lastPromiseGet = () => {
const req = MockAxios.lastReqGet();
return req ? req.promise : void 0;
};
const _findReqByPredicate = (predicate: (item: AxiosMockQueueItem) => boolean) => {
return _pending_requests
.slice()
.reverse() // reverse cloned array to return most recent req
.find(predicate);
}
const deepEqual = (x: any, y: any): boolean => {
// adapted from https://stackoverflow.com/a/16788517
// should handle most relevant edge cases (except for circular references etc.)
if (x === null || x === undefined || y === null || y === undefined) { return x === y; }
// after this just checking type of one would be enough
if (x.constructor !== y.constructor) { return false; }
// if they are functions, they should exactly refer to same one (because of closures)
if (x instanceof Function) { return x === y; }
// if they are regexps, they should exactly refer to same one (it is hard to better equality check on current ES)
if (x instanceof RegExp) { return x === y; }
if (x === y || x.valueOf() === y.valueOf()) { return true; }
if (Array.isArray(x) && x.length !== y.length) { return false; }
// if they are dates, they must had equal valueOf
if (x instanceof Date) { return false; }
// if they are strictly equal, they both need to be object at least
if (!(x instanceof Object)) { return false; }
if (!(y instanceof Object)) { return false; }
// recursive object equality check
var p = Object.keys(x);
return Object.keys(y).every(function (i) { return p.indexOf(i) !== -1; }) &&
p.every(function (i) { return deepEqual(x[i], y[i]); });
}
const _checkCriteria = (item: AxiosMockQueueItem, criteria: AxiosMockRequestCriteria) => {
if (criteria.method !== undefined && criteria.method.toLowerCase() !== item.method.toLowerCase()) {
return false;
}
if (criteria.url !== undefined && criteria.url !== item.url) {
return false;
}
if(criteria.params !== undefined) {
if(item.config === undefined || !item.config.params || (typeof item.config.params !== 'object') ) {
return false;
}
const paramsMatching = Object.entries(criteria.params).every(([key, value]) => deepEqual(item.config.params[key], value));
if(!paramsMatching) {
return false;
}
}
return true;
};
MockAxios.getReqMatching = (criteria: AxiosMockRequestCriteria) => {
return _findReqByPredicate((x) => _checkCriteria(x, criteria));
};
MockAxios.getReqByUrl = (url: string) => {
return MockAxios.getReqMatching({url});
};
MockAxios.getReqByMatchUrl = (url: RegExp) => {
return _findReqByPredicate((x) => url.test(x.url));
};
MockAxios.getReqByRegex = (opts: {[key in keyof AxiosMockQueueItem]+?: RegExp}) => {
return _findReqByPredicate(x => Object.entries(opts).every(([key, value]) => value.test(JSON.stringify(x[key]))));
};
MockAxios.queue = () => {
return _pending_requests;
};
MockAxios.reset = () => {
// remove all the requests
_pending_requests.splice(0, _pending_requests.length);
// resets all information stored in the mockFn.mock.calls and mockFn.mock.instances arrays
MockAxios.get.mockClear();
MockAxios.post.mockClear();
MockAxios.put.mockClear();
MockAxios.patch.mockClear();
MockAxios.delete.mockClear();
MockAxios.head.mockClear();
MockAxios.options.mockClear();
MockAxios.request.mockClear();
MockAxios.all.mockClear();
MockAxios.interceptors.request.clear();
MockAxios.interceptors.response.clear();
};
MockAxios.useRequestHandler = (handler: RequestHandler) => {
_requestHandler = handler;
}
MockAxios.Cancel = Cancel;
MockAxios.CancelToken = CancelToken;
MockAxios.isCancel = (u): u is Cancel => {
return !!(u && u.__CANCEL__);
};
// this is a singleton object
export default MockAxios;