-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
290 lines (261 loc) · 8.64 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
const http = require("http");
const messy = require("messy");
const expect = require("unexpected").clone().use(require("unexpected-messy"));
// TODO: Use the hopefully now-upstreamed version of this instead.
const resolveExpectedRequestProperties = require("./resolveExpectedRequestProperties");
var expectWithoutFootgunProtection = expect.clone();
// Disable the footgun protection of our Unexpected clone:
expectWithoutFootgunProtection.notifyPendingPromise = function () {};
function processMockDefinitions(mockDefinitions) {
return mockDefinitions.map(function (mockDef) {
return {
request: resolveExpectedRequestProperties(mockDef.request),
response: mockDef.response,
};
});
}
var mockDefinitionForTheCurrentTest;
var resolveNext;
var promiseForAfterEach;
var afterEachRegistered = false;
function ensureAfterEachIsRegistered() {
if (!afterEachRegistered && typeof afterEach === "function") {
afterEachRegistered = true;
afterEach(function () {
if (resolveNext) {
resolveNext();
resolveNext = undefined;
return promiseForAfterEach.finally(
() => (mockDefinitionForTheCurrentTest = undefined)
);
} else {
mockDefinitionForTheCurrentTest = undefined;
}
});
}
}
// When running in jasmine/node.js, afterEach is available immediately,
// but doesn't work within the it block. Register the hook immediately:
ensureAfterEachIsRegistered();
function createMockResponse(responseProperties) {
if (typeof responseProperties === "number") {
responseProperties = { statusCode: responseProperties };
}
responseProperties = Object.assign({ statusCode: 200 }, responseProperties);
if (responseProperties.body && typeof responseProperties.body === "object") {
if (responseProperties.headers) {
if (
!Object.keys(responseProperties.headers).some(
(headerName) => headerName.toLowerCase() === "content-type"
)
) {
responseProperties.headers = Object.assign(
{
"Content-Type": "application/json",
},
responseProperties.headers
);
}
} else {
responseProperties.headers = { "Content-Type": "application/json" };
}
}
var mockResponse = new messy.HttpResponse(responseProperties);
mockResponse.statusCode = mockResponse.statusCode || 200;
mockResponse.protocolName = mockResponse.protocolName || "HTTP";
mockResponse.protocolVersion = mockResponse.protocolVersion || "1.1";
mockResponse.statusMessage =
mockResponse.statusMessage || http.STATUS_CODES[mockResponse.statusCode];
return mockResponse;
}
// function createErrorResponse() {
// const response = new global.Response(null, {status: 0, statusText: ''});
// response.type = 'error';
// return response;
// }
function createActualRequestModel(url, opts) {
const requestProperties = Object.assign({ url, method: "GET" }, opts);
const requestBody = requestProperties.body;
if (requestBody && typeof requestBody === "object") {
if (requestProperties.headers) {
if (
!Object.keys(requestProperties.headers).some(
(headerName) => headerName.toLowerCase() === "content-type"
)
) {
requestProperties.headers = Object.assign(
{
"Content-Type": "application/json",
},
requestProperties.headers
);
}
} else {
requestProperties.headers = { "Content-Type": "application/json" };
}
}
return new messy.HttpRequest(requestProperties);
}
function verifyRequest(actualRequest, expectedRequest) {
// Handle potential oathbreaking of the assertion.
var promise;
try {
promise = expect(actualRequest, "to satisfy", expectedRequest);
} catch (e) {
promise = Promise.reject(e);
}
return promise;
}
function verifyConversation(expectedExchanges, actualConversation, err) {
return expect(actualConversation, "to satisfy", {
exchanges: expectedExchanges,
}).then(() => {
if (err) {
// The conversations matched so we will rethrow the error
throw err;
}
});
}
function fetchception(expectedExchanges, promiseFactory) {
if (!global.fetch) {
throw new Error(
"fetchception: Did not find a global.fetch. Make sure that you load a fetch polyfill if you are running your tests in an environment with no native implementation."
);
}
// When the caller left out the expectedExchanges assume they meant []
if (
typeof promiseFactory === "undefined" &&
typeof expectedExchanges === "function"
) {
promiseFactory = expectedExchanges;
expectedExchanges = [];
} else if (typeof expectedExchanges === "undefined") {
expectedExchanges = [];
}
// Allow passing a single exchange pair without wrapping it in an object.
if (
expectedExchanges &&
typeof expectedExchanges === "object" &&
!Array.isArray(expectedExchanges)
) {
expectedExchanges = [expectedExchanges];
}
expectedExchanges = expectedExchanges.map((expectedExchange) => {
// FIXME: Should be supported directly by messy
if (
expectedExchange.request &&
typeof expectedExchange.request.url === "string"
) {
const matchMethodInUrl =
expectedExchange.request.url.match(/^([A-Z]+) ([\s\S]*)$/);
if (matchMethodInUrl) {
const fixedRequest = Object.assign({}, expectedExchange.request);
fixedRequest.method = matchMethodInUrl[1];
fixedRequest.url = matchMethodInUrl[2];
expectedExchange = {
request: fixedRequest,
response: expectedExchange.response,
};
}
}
return expectedExchange;
});
if (mockDefinitionForTheCurrentTest) {
Array.prototype.push.apply(
mockDefinitionForTheCurrentTest,
expectedExchanges
);
if (!promiseFactory) {
return;
}
} else {
mockDefinitionForTheCurrentTest = expectedExchanges;
}
const originalFetch = global.fetch;
const restoreFetch = () => (global.fetch = originalFetch);
const httpConversation = new messy.HttpConversation();
mockDefinitionForTheCurrentTest = processMockDefinitions(
mockDefinitionForTheCurrentTest
);
let exchangeIndex = 0;
function getNextExchange() {
const exchange = mockDefinitionForTheCurrentTest[exchangeIndex] || {};
exchangeIndex += 1;
return {
request: exchange.request,
response: exchange.response,
};
}
global.fetch = (url, opts) => {
mockDefinitionForTheCurrentTest = processMockDefinitions(
mockDefinitionForTheCurrentTest
);
const currentExchange = getNextExchange();
const actualRequest = createActualRequestModel(url, opts);
const mockResponse = createMockResponse(currentExchange.response);
return verifyRequest(actualRequest, currentExchange.request).then(
(res) => {
httpConversation.exchanges.push(
new messy.HttpExchange({
request: actualRequest,
response: mockResponse,
})
);
const response = new global.Response(mockResponse.decodedBody, {
status: mockResponse.statusLine.statusCode,
statusText: mockResponse.statusLine.statusMessage,
headers: mockResponse.headers.valuesByName,
});
return response;
},
() => {
// the request didn't match, so we create a failing response to
// break the code asap
const error = new TypeError("Network request failed");
httpConversation.exchanges.push(
new messy.HttpExchange({
request: actualRequest,
response: mockResponse,
})
);
throw error;
}
);
};
if (promiseFactory) {
const promise = promiseFactory(); // TODO: handle throws
if (!promise || typeof promise.then !== "function") {
restoreFetch();
throw new Error(
"fetchception: You must return a promise from the supplied function."
);
}
resolveNext = false;
return expect
.promise(() => promise)
.then(
() =>
verifyConversation(mockDefinitionForTheCurrentTest, httpConversation),
(err) =>
verifyConversation(
mockDefinitionForTheCurrentTest,
httpConversation,
err
)
)
.finally(() => restoreFetch());
} else {
promiseForAfterEach = expectWithoutFootgunProtection(function () {
return expect.promise((resolve, reject) => {
resolveNext = resolve;
});
}, "not to error")
.then(() =>
verifyConversation(mockDefinitionForTheCurrentTest, httpConversation)
)
.finally(() => restoreFetch());
}
}
module.exports = fetchception;
// Expose the internal unexpected instance.
module.exports.expect = expect;