forked from pretenderjs/FakeXMLHttpRequest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fake_xml_http_request.js
509 lines (432 loc) · 13.8 KB
/
fake_xml_http_request.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
global.FakeXMLHttpRequest = factory()
}(this, function () { 'use strict';
/**
* Minimal Event interface implementation
*
* Original implementation by Sven Fuchs: https://gist.github.com/995028
* Modifications and tests by Christian Johansen.
*
* @author Sven Fuchs ([email protected])
* @author Christian Johansen ([email protected])
* @license BSD
*
* Copyright (c) 2011 Sven Fuchs, Christian Johansen
*/
var _Event = function Event(type, bubbles, cancelable, target) {
this.type = type;
this.bubbles = bubbles;
this.cancelable = cancelable;
this.target = target;
};
_Event.prototype = {
stopPropagation: function () {},
preventDefault: function () {
this.defaultPrevented = true;
}
};
/*
Used to set the statusText property of an xhr object
*/
var httpStatusCodes = {
100: "Continue",
101: "Switching Protocols",
200: "OK",
201: "Created",
202: "Accepted",
203: "Non-Authoritative Information",
204: "No Content",
205: "Reset Content",
206: "Partial Content",
300: "Multiple Choice",
301: "Moved Permanently",
302: "Found",
303: "See Other",
304: "Not Modified",
305: "Use Proxy",
307: "Temporary Redirect",
400: "Bad Request",
401: "Unauthorized",
402: "Payment Required",
403: "Forbidden",
404: "Not Found",
405: "Method Not Allowed",
406: "Not Acceptable",
407: "Proxy Authentication Required",
408: "Request Timeout",
409: "Conflict",
410: "Gone",
411: "Length Required",
412: "Precondition Failed",
413: "Request Entity Too Large",
414: "Request-URI Too Long",
415: "Unsupported Media Type",
416: "Requested Range Not Satisfiable",
417: "Expectation Failed",
422: "Unprocessable Entity",
500: "Internal Server Error",
501: "Not Implemented",
502: "Bad Gateway",
503: "Service Unavailable",
504: "Gateway Timeout",
505: "HTTP Version Not Supported"
};
/*
Cross-browser XML parsing. Used to turn
XML responses into Document objects
Borrowed from JSpec
*/
function parseXML(text) {
var xmlDoc;
if (typeof DOMParser != "undefined") {
var parser = new DOMParser();
xmlDoc = parser.parseFromString(text, "text/xml");
} else {
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(text);
}
return xmlDoc;
}
/*
Without mocking, the native XMLHttpRequest object will throw
an error when attempting to set these headers. We match this behavior.
*/
var unsafeHeaders = {
"Accept-Charset": true,
"Accept-Encoding": true,
"Connection": true,
"Content-Length": true,
"Cookie": true,
"Cookie2": true,
"Content-Transfer-Encoding": true,
"Date": true,
"Expect": true,
"Host": true,
"Keep-Alive": true,
"Referer": true,
"TE": true,
"Trailer": true,
"Transfer-Encoding": true,
"Upgrade": true,
"User-Agent": true,
"Via": true
};
/*
Adds an "event" onto the fake xhr object
that just calls the same-named method. This is
in case a library adds callbacks for these events.
*/
function _addEventListener(eventName, xhr){
xhr.addEventListener(eventName, function (event) {
var listener = xhr["on" + eventName];
if (listener && typeof listener == "function") {
listener(event);
}
});
}
function EventedObject() {
this._eventListeners = {};
var events = ["loadstart", "progress", "load", "abort", "loadend"];
for (var i = events.length - 1; i >= 0; i--) {
_addEventListener(events[i], this);
}
};
EventedObject.prototype = {
/*
Duplicates the behavior of native XMLHttpRequest's addEventListener function
*/
addEventListener: function addEventListener(event, listener) {
this._eventListeners[event] = this._eventListeners[event] || [];
this._eventListeners[event].push(listener);
},
/*
Duplicates the behavior of native XMLHttpRequest's removeEventListener function
*/
removeEventListener: function removeEventListener(event, listener) {
var listeners = this._eventListeners[event] || [];
for (var i = 0, l = listeners.length; i < l; ++i) {
if (listeners[i] == listener) {
return listeners.splice(i, 1);
}
}
},
/*
Duplicates the behavior of native XMLHttpRequest's dispatchEvent function
*/
dispatchEvent: function dispatchEvent(event) {
var type = event.type;
var listeners = this._eventListeners[type] || [];
for (var i = 0; i < listeners.length; i++) {
if (typeof listeners[i] == "function") {
listeners[i].call(this, event);
} else {
listeners[i].handleEvent(event);
}
}
return !!event.defaultPrevented;
},
/*
Triggers an `onprogress` event with the given parameters.
*/
_progress: function _progress(lengthComputable, loaded, total) {
var event = new _Event('progress');
event.target = this;
event.lengthComputable = lengthComputable;
event.loaded = loaded;
event.total = total;
this.dispatchEvent(event);
}
}
/*
Constructor for a fake window.XMLHttpRequest
*/
function FakeXMLHttpRequest() {
EventedObject.call(this);
this.readyState = FakeXMLHttpRequest.UNSENT;
this.requestHeaders = {};
this.requestBody = null;
this.status = 0;
this.statusText = "";
this.upload = new EventedObject();
}
FakeXMLHttpRequest.prototype = new EventedObject();
// These status codes are available on the native XMLHttpRequest
// object, so we match that here in case a library is relying on them.
FakeXMLHttpRequest.UNSENT = 0;
FakeXMLHttpRequest.OPENED = 1;
FakeXMLHttpRequest.HEADERS_RECEIVED = 2;
FakeXMLHttpRequest.LOADING = 3;
FakeXMLHttpRequest.DONE = 4;
var FakeXMLHttpRequestProto = {
UNSENT: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4,
async: true,
withCredentials: false,
/*
Duplicates the behavior of native XMLHttpRequest's open function
*/
open: function open(method, url, async, username, password) {
this.method = method;
this.url = url;
this.async = typeof async == "boolean" ? async : true;
this.username = username;
this.password = password;
this.responseText = null;
this.responseXML = null;
this.requestHeaders = {};
this.sendFlag = false;
this._readyStateChange(FakeXMLHttpRequest.OPENED);
},
/*
Duplicates the behavior of native XMLHttpRequest's setRequestHeader function
*/
setRequestHeader: function setRequestHeader(header, value) {
verifyState(this);
if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) {
throw new Error("Refused to set unsafe header \"" + header + "\"");
}
if (this.requestHeaders[header]) {
this.requestHeaders[header] += "," + value;
} else {
this.requestHeaders[header] = value;
}
},
/*
Duplicates the behavior of native XMLHttpRequest's send function
*/
send: function send(data) {
verifyState(this);
if (!/^(get|head)$/i.test(this.method)) {
if (!this.requestHeaders["Content-Type"] && !(data || '').toString().match('FormData')) {
this.requestHeaders["Content-Type"] = "text/plain;charset=UTF-8";
}
this.requestBody = data;
}
this.errorFlag = false;
this.sendFlag = this.async;
this._readyStateChange(FakeXMLHttpRequest.OPENED);
if (typeof this.onSend == "function") {
this.onSend(this);
}
this.dispatchEvent(new _Event("loadstart", false, false, this));
},
/*
Duplicates the behavior of native XMLHttpRequest's abort function
*/
abort: function abort() {
this.aborted = true;
this.responseText = null;
this.errorFlag = true;
this.requestHeaders = {};
if (this.readyState > FakeXMLHttpRequest.UNSENT && this.sendFlag) {
this._readyStateChange(FakeXMLHttpRequest.DONE);
this.sendFlag = false;
}
this.readyState = FakeXMLHttpRequest.UNSENT;
this.dispatchEvent(new _Event("abort", false, false, this));
if (typeof this.onerror === "function") {
this.onerror();
}
},
/*
Duplicates the behavior of native XMLHttpRequest's getResponseHeader function
*/
getResponseHeader: function getResponseHeader(header) {
if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
return null;
}
if (/^Set-Cookie2?$/i.test(header)) {
return null;
}
header = header.toLowerCase();
for (var h in this.responseHeaders) {
if (h.toLowerCase() == header) {
return this.responseHeaders[h];
}
}
return null;
},
/*
Duplicates the behavior of native XMLHttpRequest's getAllResponseHeaders function
*/
getAllResponseHeaders: function getAllResponseHeaders() {
if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) {
return "";
}
var headers = "";
for (var header in this.responseHeaders) {
if (this.responseHeaders.hasOwnProperty(header) && !/^Set-Cookie2?$/i.test(header)) {
headers += header + ": " + this.responseHeaders[header] + "\r\n";
}
}
return headers;
},
/*
Duplicates the behavior of native XMLHttpRequest's overrideMimeType function
*/
overrideMimeType: function overrideMimeType(mimeType) {
if (typeof mimeType === "string") {
this.forceMimeType = mimeType.toLowerCase();
}
},
/*
Places a FakeXMLHttpRequest object into the passed
state.
*/
_readyStateChange: function _readyStateChange(state) {
this.readyState = state;
if (typeof this.onreadystatechange == "function") {
this.onreadystatechange(new _Event("readystatechange"));
}
this.dispatchEvent(new _Event("readystatechange"));
if (this.readyState == FakeXMLHttpRequest.DONE) {
this.dispatchEvent(new _Event("load", false, false, this));
this.dispatchEvent(new _Event("loadend", false, false, this));
}
},
/*
Sets the FakeXMLHttpRequest object's response headers and
places the object into readyState 2
*/
_setResponseHeaders: function _setResponseHeaders(headers) {
this.responseHeaders = {};
for (var header in headers) {
if (headers.hasOwnProperty(header)) {
this.responseHeaders[header] = headers[header];
}
}
if (this.forceMimeType) {
this.responseHeaders['Content-Type'] = this.forceMimeType;
}
if (this.async) {
this._readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED);
} else {
this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED;
}
},
/*
Sets the FakeXMLHttpRequest object's response body and
if body text is XML, sets responseXML to parsed document
object
*/
_setResponseBody: function _setResponseBody(body) {
verifyRequestSent(this);
verifyHeadersReceived(this);
verifyResponseBodyType(body);
var chunkSize = this.chunkSize || 10;
var index = 0;
this.responseText = "";
do {
if (this.async) {
this._readyStateChange(FakeXMLHttpRequest.LOADING);
}
this.responseText += body.substring(index, index + chunkSize);
index += chunkSize;
} while (index < body.length);
var type = this.getResponseHeader("Content-Type");
if (this.responseText && (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) {
try {
this.responseXML = parseXML(this.responseText);
} catch (e) {
// Unable to parse XML - no biggie
}
}
if (this.async) {
this._readyStateChange(FakeXMLHttpRequest.DONE);
} else {
this.readyState = FakeXMLHttpRequest.DONE;
}
},
/*
Forces a response on to the FakeXMLHttpRequest object.
This is the public API for faking responses. This function
takes a number status, headers object, and string body:
```
xhr.respond(404, {Content-Type: 'text/plain'}, "Sorry. This object was not found.")
```
*/
respond: function respond(status, headers, body) {
this._setResponseHeaders(headers || {});
this.status = typeof status == "number" ? status : 200;
this.statusText = httpStatusCodes[this.status];
this._setResponseBody(body || "");
}
};
for (var property in FakeXMLHttpRequestProto) {
FakeXMLHttpRequest.prototype[property] = FakeXMLHttpRequestProto[property];
}
function verifyState(xhr) {
if (xhr.readyState !== FakeXMLHttpRequest.OPENED) {
throw new Error("INVALID_STATE_ERR");
}
if (xhr.sendFlag) {
throw new Error("INVALID_STATE_ERR");
}
}
function verifyRequestSent(xhr) {
if (xhr.readyState == FakeXMLHttpRequest.DONE) {
throw new Error("Request done");
}
}
function verifyHeadersReceived(xhr) {
if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) {
throw new Error("No headers received");
}
}
function verifyResponseBodyType(body) {
if (typeof body != "string") {
var error = new Error("Attempted to respond to fake XMLHttpRequest with " +
body + ", which is not a string.");
error.name = "InvalidBodyException";
throw error;
}
}
var fake_xml_http_request = FakeXMLHttpRequest;
return fake_xml_http_request;
}));