-
Notifications
You must be signed in to change notification settings - Fork 89
/
index.js
417 lines (372 loc) · 11.2 KB
/
index.js
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
406
407
408
409
410
411
412
413
414
415
416
417
import axios from 'axios'
import buildURL from 'axios/lib/helpers/buildURL'
import isURLSameOrigin from 'axios/lib/helpers/isURLSameOrigin'
import btoa from 'axios/lib/helpers/btoa'
import cookies from 'axios/lib/helpers/cookies'
import settle from 'axios/lib/core/settle'
import createError from 'axios/lib/core/createError'
const TimeoutException = new Error('Timeout: Stub function not called.')
const DEFAULT_WAIT_DELAY = 1
// The default adapter
let defaultAdapter
/**
* Check if a tracked stub or request matches a request by comparing URL and method
*
* @param {Object} tracked An item of a Tracker instance
* @param {Object} request A Request
* @param {String} [baseURL] The base URL of the request config
* @return {boolean} Whether or not the request is a match for the tracked item
*/
let matchRequest = (tracked, request, baseURL = '') => {
let matchedURL = false
let matchedMethod = true
if (tracked.url instanceof RegExp) {
matchedURL = tracked.url.test(request.url)
} else if (request.url instanceof RegExp) {
matchedURL = request.url.test(tracked.url)
} else {
matchedURL = `${baseURL || ''}${tracked.url}` === request.url
}
if (tracked.method) {
// Stub tracking
matchedMethod = request.config.method.toLowerCase() === tracked.method.toLowerCase()
} else if (tracked.config && tracked.config.method) {
// Request tracking
matchedMethod = request.config.method.toLowerCase() === tracked.config.method.toLowerCase()
}
return matchedURL && matchedMethod
}
/**
* The mock adapter that gets installed.
*
* @param {Function} resolve The function to call when Promise is resolved
* @param {Function} reject The function to call when Promise is rejected
* @param {Object} config The config object to be used for the request
*/
let mockAdapter = (config) => {
return new Promise(function (resolve, reject) {
let request = new Request(resolve, reject, config)
moxios.requests.track(request)
// Check for matching stub to auto respond with
for (let i=0, l=moxios.stubs.count(); i<l; i++) {
let stub = moxios.stubs.at(i)
if (matchRequest(stub, request, config && config.baseURL)) {
if (stub.timeout) {
throwTimeout(config)
}
request.respondWith(stub.response)
stub.resolve()
break
}
}
});
}
/**
* create common object for timeout response
*
* @param {object} config The config object to be used for the request
*/
let createTimeout = (config) => {
return createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED')
}
/**
* throw common error for timeout response
*
* @param {object} config The config object to be used for the request
*/
let throwTimeout = (config) => {
throw createTimeout(config)
}
class Tracker {
constructor() {
this.__items = []
}
/**
* Reset all the items being tracked
*/
reset() {
this.__items.splice(0)
}
/**
* Add an item to be tracked
*
* @param {Object} item An item to be tracked
*/
track(item) {
this.__items.push(item)
}
/**
* The count of items being tracked
*
* @return {Number}
*/
count() {
return this.__items.length
}
/**
* Get an item being tracked at a given index
*
* @param {Number} index The index for the item to retrieve
* @return {Object}
*/
at(index) {
return this.__items[index]
}
/**
* Get the first item being tracked
*
* @return {Object}
*/
first() {
return this.at(0)
}
/**
* Get the most recent (last) item being tracked
*
* @return {Object}
*/
mostRecent() {
return this.at(this.count() - 1)
}
/**
* Dump the items being tracked to the console.
*/
debug() {
console.log();
this.__items.forEach((element) => {
let output;
if (element.config) {
// request
output = element.config.method.toLowerCase() + ', ';
output += element.config.url;
} else {
// stub
output = element.method.toLowerCase() + ', ';
output += element.url + ', ';
output += element.response.status + ', ';
if (element.response.response) {
output += JSON.stringify(element.response.response);
} else {
output += '{}';
}
}
console.log(output);
});
}
/**
* Find and return element given the HTTP method and the URL.
*/
get(method, url) {
// Mock a request config
let request = {
url,
config: { method }
}
return this.__items.find((item) => matchRequest(item, request));
}
/**
* Stop an element from being tracked by removing it. Finds and returns the element,
* given the HTTP method and the URL.
*/
remove(method, url) {
let elem = this.get(method, url);
let index = this.__items.indexOf(elem);
return this.__items.splice(index, 1)[0];
}
}
class Request {
/**
* Create a new Request object
*
* @param {Function} resolve The function to call when Promise is resolved
* @param {Function} reject The function to call when Promise is rejected
* @param {Object} config The config object to be used for the request
*/
constructor(resolve, reject, config) {
this.resolve = resolve
this.reject = reject
this.config = config
this.headers = config.headers
this.url = buildURL(config.url, config.params, config.paramsSerializer)
this.timeout = config.timeout
this.withCredentials = config.withCredentials || false
this.responseType = config.responseType
// Set auth header
if (config.auth) {
let username = config.auth.username || ''
let password = config.auth.password || ''
this.headers.Authorization = 'Basic ' + btoa(username + ':' + password)
}
// Set xsrf header
if (typeof document !== 'undefined' && typeof document.cookie !== 'undefined') {
let xsrfValue = config.withCredentials || isURLSameOrigin(config.url) ?
cookies.read(config.xsrfCookieName) :
undefined
if (xsrfValue) {
this.headers[config.xsrfHeaderName] = xsrfValue
}
}
}
/**
* Respond to this request with a timeout result
*
* @return {Promise} A Promise that rejects with a timeout result
*/
respondWithTimeout() {
let response = new Response(this, createTimeout(this.config))
settle(this.resolve, this.reject, response)
return new Promise(function(resolve, reject) {
moxios.wait(function() {
reject(response)
})
})
}
/**
* Respond to this request with a specified result
*
* @param {Object} res The data representing the result of the request
* @return {Promise} A Promise that resolves once the response is ready
*/
respondWith(res) {
let response = new Response(this, res)
settle(this.resolve, this.reject, response)
return new Promise(function (resolve) {
moxios.wait(function () {
resolve(response)
})
})
}
}
class Response {
/**
* Create a new Response object
*
* @param {Request} req The Request that this Response is associated with
* @param {Object} res The data representing the result of the request
*/
constructor(req, res) {
this.config = req.config
this.data = res.responseText || res.response;
this.status = res.status
this.statusText = res.statusText
/* lowecase all headers keys to be consistent with Axios */
if ('headers' in res) {
let newHeaders = {};
for (let header in res.headers) {
newHeaders[header.toLowerCase()] = res.headers[header];
}
res.headers = newHeaders;
}
this.headers = res.headers
this.request = req
this.code = res.code
}
}
let moxios = {
stubs: new Tracker(),
requests: new Tracker(),
delay: DEFAULT_WAIT_DELAY,
timeoutException: TimeoutException,
/**
* Install the mock adapter for axios
*/
install: function(instance = axios) {
defaultAdapter = instance.defaults.adapter
instance.defaults.adapter = mockAdapter
},
/**
* Uninstall the mock adapter and reset state
*/
uninstall: function(instance = axios) {
instance.defaults.adapter = defaultAdapter
this.stubs.reset()
this.requests.reset()
},
/**
* Stub a response to be used to respond to a request matching a method and a URL or RegExp
* The first parameter is optional for backwards compatability reasons. It might change to
* a required parameter in the future. Please always specify a method
*
* @param {String} [method] An axios command
* @param {String|RegExp} urlOrRegExp A URL or RegExp to test against
* @param {Object} response The response to use when a match is made
*/
stubRequest: function(...args) {
if (args.length === 3) {
this.stubs.track({method: args[0], url: args[1], response: args[2]});
} else {
this.stubs.track({url: args[0], response: args[1]});
}
},
/**
* Stub a response to be used one or more times to respond to a request matching a
* method and a URL or RegExp.
*
* @param {String} method An axios command
* @param {String|RegExp} urlOrRegExp A URL or RegExp to test against
* @param {Object} response The response to use when a match is made
*/
stubOnce: function (method, urlOrRegExp, response) {
return new Promise((resolve) => {
this.stubs.track({url: urlOrRegExp, method, response, resolve});
});
},
/**
* Stub a timed response to a request matching a method and a URL or RegExp. If
* timer fires, reject with a TimeoutException for simple assertions. The goal is
* to show that a certain request was not made.
*
* @param {String} method An axios command
* @param {String|RegExp} urlOrRegExp A URL or RegExp to test against
* @param {Object} response The response to use when a match is made
*/
stubFailure: function (method, urlOrRegExp, response) {
return new Promise((resolve, reject) => {
this.stubs.track({url: urlOrRegExp, method, response, resolve});
setTimeout(function() {
reject(TimeoutException);
}, 500);
});
},
/**
* Stub a timeout to be used to respond to a request matching a URL or RegExp
*
* @param {String|RegExp} urlOrRegExp A URL or RegExp to test against
*/
stubTimeout: function(urlOrRegExp) {
this.stubs.track({url: urlOrRegExp, timeout: true})
},
/**
* Run a single test with mock adapter installed.
* This will install the mock adapter, execute the function provided,
* then uninstall the mock adapter once complete.
*
* @param {Function} fn The function to be executed
*/
withMock: function(fn) {
this.install()
try {
fn()
} finally {
this.uninstall()
}
},
/**
* Wait for request to be made before proceding.
* This is naively using a `setTimeout`.
* May need to beef this up a bit in the future.
*
* @param {Function} fn Optional function to execute once waiting is over
* @param {Number} delay How much time in milliseconds to wait
*
* @return {Object} Promise that gets resolved when waiting completed
*/
wait: function(...args) {
const cb = typeof args[0] === 'function' ? args.shift() : null
const delay = typeof args[0] !== 'undefined' ? args.shift() : this.delay
return new Promise(resolve => {
setTimeout(resolve, delay)
}).then(cb);
}
}
export default moxios