-
Notifications
You must be signed in to change notification settings - Fork 90
/
index.js
278 lines (248 loc) · 6.85 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
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 DEFAULT_WAIT_DELAY = 100
// The default adapter
let defaultAdapter
/**
* 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 (stub.url === request.url ||
stub.url instanceof RegExp && stub.url.test(request.url)) {
if (stub.timeout) {
throwTimeout(config)
}
request.respondWith(stub.response)
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)
}
}
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
this.headers = res.headers
this.request = req
this.code = res.code
}
}
let moxios = {
stubs: new Tracker(),
requests: new Tracker(),
delay: DEFAULT_WAIT_DELAY,
/**
* 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 URL or RegExp
*
* @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(urlOrRegExp, response) {
this.stubs.track({url: urlOrRegExp, response})
},
/**
* 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 The function to execute once waiting is over
* @param {Number} delay How much time in milliseconds to wait
*/
wait: function(fn, delay = this.delay) {
setTimeout(fn, delay)
}
}
export default moxios