-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathmock-resource.js
263 lines (230 loc) · 6.23 KB
/
mock-resource.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
import { configs } from '../mappersmith'
import MockRequest from './mock-request'
import Request from '../request'
const VALUE_NOT_MATCHED = '<MAPPERSMITH_VALUE_NOT_MATCHED>'
/**
* @param {Integer} id
* @param {Object} client - the client generated by {@link forge}
*/
function MockResource(id, client) {
if (!client || !client._manifest) {
throw new Error('[Mappersmith Test] "mockClient" received an invalid client')
}
this.id = id
this.manifest = client._manifest
this.resourceName = null
this.mockName = null
this.methodName = null
this.requestParams = {}
this.responseData = null
this.responseHandler = null
this.responseHeaders = {}
this.responseStatus = 200
this.responseStatusHandler = null
this.mockRequest = null
this.asyncFinalRequest = null
this.pendingMiddlewareExecution = true
}
MockResource.prototype = {
/**
* @return {MockResource}
*/
resource(resourceName) {
this.resourceName = resourceName
return this
},
/**
* Names you mock instance for debugging purposes.
* @return {MockResource}
*/
named(mockName) {
this.mockName = mockName
return this
},
/**
* Creates a name for the mock based on the client id and the resource name.
* @returns {String}
*/
getName() {
const { mockName, manifest, resourceName, id } = this
const { clientId } = manifest || {}
if (mockName) return mockName
const resourcePart = resourceName || id
if (clientId) {
return `${clientId} - ${resourcePart}`
}
return resourceName ? `${resourceName} - ${id}` : id
},
/**
* @return {MockResource}
*/
method(methodName) {
this.methodName = methodName
return this
},
/**
* @return {MockResource}
*/
with(requestParams) {
this.requestParams = requestParams
return this
},
/**
* @return {MockResource}
*/
headers(responseHeaders) {
this.responseHeaders = responseHeaders
return this
},
/**
* @return {MockResource}
*/
status(responder) {
if (typeof responder === 'function') {
this.responseStatusHandler = responder
} else {
this.responseStatus = responder
}
return this
},
/**
* @return {MockResource}
*/
response(responder) {
if (typeof responder === 'function') {
this.responseHandler = responder
} else {
this.responseData = responder
}
return this
},
/**
* @return {Promise<MockAssert>}
*/
assertObjectAsync() {
return this.createAsyncRequest().then((finalRequest) => {
this.asyncFinalRequest = finalRequest
this.pendingMiddlewareExecution = false
return this.toMockRequest().assertObject()
})
},
/**
* @return {MockAssert}
*/
assertObject() {
// The middleware "prepareRequest" phase is always async, so the middleware
// stack will never run when assertObject is used
return this.toMockRequest().assertObject()
},
/**
* @return {MockRequest}
*/
toMockRequest() {
const finalRequest = this.asyncFinalRequest ? this.asyncFinalRequest : this.createRequest()
const responseStatus = this.responseStatusHandler || this.responseStatus
if (!this.mockRequest) {
this.mockRequest = new MockRequest(this.id, {
mockName: this.getName(),
method: finalRequest.method(),
url: this.generateUrlMatcher(finalRequest),
body: finalRequest.body(),
headers: finalRequest.headers(),
response: {
status: responseStatus,
headers: this.responseHeaders,
body: this.responseData,
handler: this.responseHandler,
},
})
}
return this.mockRequest
},
/**
* @private
*/
generateUrlMatcher(finalRequest) {
const params = finalRequest.params()
const hasParamMatchers = Object.keys(params).find((key) => typeof params[key] === 'function')
if (!hasParamMatchers) {
return finalRequest.url()
}
const urlMatcher = (requestUrl, requestParams) => {
const additionalParams = this.evaluateParamMatchers(params, requestParams)
const testRequest = finalRequest.enhance({ params: additionalParams })
return testRequest.url() === requestUrl
}
return urlMatcher
},
/**
* @private
*/
executeMiddlewareStack() {
return this.createAsyncRequest().then((finalRequest) => {
this.asyncFinalRequest = finalRequest
if (this.mockRequest) {
const urlMatcher = this.generateUrlMatcher(finalRequest)
this.mockRequest.url = urlMatcher
this.mockRequest.body = finalRequest.body()
this.pendingMiddlewareExecution = false
}
})
},
/**
* @private
*/
evaluateParamMatchers(mockParams, requestParams) {
return Object.keys(mockParams).reduce((obj, key) => {
const matcher = mockParams[key]
if (typeof matcher !== 'function') {
return obj
}
const value = requestParams[key]
// Only evaluate if key was provided in request params.
// Otherwise we always consider it not to match.
if (key in requestParams && matcher(value)) {
obj[key] = value
} else {
obj[key] = VALUE_NOT_MATCHED
}
return obj
}, {})
},
/**
* @private
* It never runs the middleware stack
*/
createRequest() {
const methodDescriptor = this.manifest.createMethodDescriptor(
this.resourceName,
this.methodName
)
return new Request(methodDescriptor, this.requestParams)
},
/**
* @private
* Always runs the middleware stack
*/
createAsyncRequest() {
const methodDescriptor = this.manifest.createMethodDescriptor(
this.resourceName,
this.methodName
)
const initialRequest = new Request(methodDescriptor, this.requestParams)
const middleware = this.manifest.createMiddleware({
resourceName: this.resourceName,
resourceMethod: this.methodName,
mockRequest: true,
})
const abort = (error) => {
throw error
}
const getInitialRequest = () => configs.Promise.resolve(initialRequest)
const prepareRequest = middleware.reduce(
(next, middleware) => () =>
configs.Promise.resolve().then(() => middleware.prepareRequest(next, abort)),
getInitialRequest
)
return prepareRequest()
},
}
export default MockResource