forked from jakerella/jquery-mockjax
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery.mockjax.js
416 lines (383 loc) · 12.6 KB
/
jquery.mockjax.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
/*!
* MockJax - jQuery Plugin to Mock Ajax requests
*
* Version: 1.5.0pre
* Released:
* Home: http://github.com/appendto/jquery-mockjax
* Author: Jonathan Sharp (http://jdsharp.com)
* License: MIT,GPL
*
* Copyright (c) 2011 appendTo LLC.
* Dual licensed under the MIT or GPL licenses.
* http://appendto.com/open-source-licenses
*/
(function($) {
var _ajax = $.ajax,
mockHandlers = [];
function parseXML(xml) {
if ( window['DOMParser'] == undefined && window.ActiveXObject ) {
DOMParser = function() { };
DOMParser.prototype.parseFromString = function( xmlString ) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML( xmlString );
return doc;
};
}
try {
var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' );
if ( $.isXMLDoc( xmlDoc ) ) {
var err = $('parsererror', xmlDoc);
if ( err.length == 1 ) {
throw('Error: ' + $(xmlDoc).text() );
}
} else {
throw('Unable to parse XML');
}
} catch( e ) {
var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );
$(document).trigger('xmlParseError', [ msg ]);
return undefined;
}
return xmlDoc;
}
$.extend({
ajax: function(url, origSettings) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
origSettings = url;
url = undefined;
} else {
// work around to support 1.5 signature
origSettings.url = url;
}
var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings),
mock = false;
// Iterate over our mock handlers (in registration order) until we find
// one that is willing to intercept the request
$.each(mockHandlers, function(k, v) {
if ( !mockHandlers[k] ) {
return;
}
var m = null;
// If the mock was registered with a function, let the function decide if we
// want to mock this request
if ( $.isFunction(mockHandlers[k]) ) {
m = mockHandlers[k](s);
} else {
m = mockHandlers[k];
// Inspect the URL of the request and check if the mock handler's url
// matches the url for this ajax request
if ( $.isFunction(m.url.test) ) {
// The user provided a regex for the url, test it
if ( !m.url.test( s.url ) ) {
m = null;
}
} else {
// Look for a simple wildcard '*' or a direct URL match
var star = m.url.indexOf('*');
if (m.url !== s.url && star === -1 || !new RegExp(m.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace('*', '.+')).test(s.url)) {
m = null;
}
}
if ( m ) {
// Inspect the data submitted in the request (either POST body or GET query string)
if ( m.data && s.data ) {
var identical = false;
// Deep inspect the identity of the objects
(function ident(mock, live) {
// Test for situations where the data is a querystring (not an object)
if (typeof live === 'string') {
// Querystring may be a regex
identical = $.isFunction( mock.test ) ? mock.test(live) : mock == live;
return identical;
}
$.each(mock, function(k, v) {
if ( live[k] === undefined ) {
identical = false;
return false;
} else {
identical = true;
if ( typeof live[k] == 'object' ) {
return ident(mock[k], live[k]);
} else {
if ( $.isFunction( mock[k].test ) ) {
identical = mock[k].test(live[k]);
} else {
identical = ( mock[k] == live[k] );
}
return identical;
}
}
});
})(m.data, s.data);
// They're not identical, do not mock this request
if ( identical == false ) {
m = null;
}
}
// Inspect the request type
if ( m && m.type && m.type.toLowerCase() != s.type.toLowerCase() ) {
// The request type doesn't match (GET vs. POST)
m = null;
}
}
}
if ( m ) {
mock = true;
// Handle console logging
var c = $.extend({}, $.mockjaxSettings, m);
if ( c.log && $.isFunction(c.log) ) {
c.log('MOCK ' + s.type.toUpperCase() + ': ' + s.url, $.extend({}, s));
}
var jsre = /=\?(&|$)/, jsc = (new Date()).getTime();
// Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
// because there isn't an easy hook for the cross domain script tag of jsonp
if ( s.dataType === "jsonp" ) {
if ( s.type.toUpperCase() === "GET" ) {
if ( !jsre.test( s.url ) ) {
s.url += (/\?/.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
}
} else if ( !s.data || !jsre.test(s.data) ) {
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
}
s.dataType = "json";
}
// Build temporary JSONP function
if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
jsonp = s.jsonpCallback || ("jsonp" + jsc++);
// Replace the =? sequence both in the query string and the data
if ( s.data ) {
s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
}
s.url = s.url.replace(jsre, "=" + jsonp + "$1");
// We need to make sure
// that a JSONP style response is executed properly
s.dataType = "script";
// Handle JSONP-style loading
window[ jsonp ] = window[ jsonp ] || function( tmp ) {
data = tmp;
success();
complete();
// Garbage collect
window[ jsonp ] = undefined;
try {
delete window[ jsonp ];
} catch(e) {}
if ( head ) {
head.removeChild( script );
}
};
}
var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
parts = rurl.exec( s.url ),
remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
// Test if we are going to create a script tag (if so, intercept & mock)
if ( s.dataType === "script" && s.type.toUpperCase() === "GET" && remote ) {
// Synthesize the mock request for adding a script tag
var callbackContext = origSettings && origSettings.context || s;
function success() {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( callbackContext, ( m.response ? m.response.toString() : m.responseText || ''), status, {} );
}
// Fire the global callback
if ( s.global ) {
trigger( "ajaxSuccess", [{}, s] );
}
}
function complete() {
// Process result
if ( s.complete ) {
s.complete.call( callbackContext, {} , status );
}
// The request was completed
if ( s.global ) {
trigger( "ajaxComplete", [{}, s] );
}
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
}
function trigger(type, args) {
(s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
}
if ( m.response && $.isFunction(m.response) ) {
m.response(origSettings);
} else {
$.globalEval(m.responseText);
}
success();
complete();
return false;
}
m.data = s.data;
m.cache = s.cache;
m.timeout = s.timeout;
m.global = s.global;
mock = _ajax.call($, $.extend(true, {}, origSettings, {
// Mock the XHR object
xhr: function() {
// Extend with our default mockjax settings
m = $.extend({}, $.mockjaxSettings, m);
if (typeof m.headers === 'undefined') {
m.headers = {};
}
if ( m.contentType ) {
m.headers['content-type'] = m.contentType;
}
// Return our mock xhr object
return {
status: m.status,
statusText: m.statusText,
readyState: 1,
open: function() { },
send: function() {
mockHandlers[k].fired = true;
// This is a substitute for < 1.4 which lacks $.proxy
var process = (function(that) {
return function() {
return (function() {
// The request has returned
this.status = m.status;
this.statusText = m.statusText;
this.readyState = 4;
// We have an executable function, call it to give
// the mock handler a chance to update it's data
if ( $.isFunction(m.response) ) {
m.response(origSettings);
}
// Copy over our mock to our xhr object before passing control back to
// jQuery's onreadystatechange callback
if ( s.dataType == 'json' && ( typeof m.responseText == 'object' ) ) {
this.responseText = JSON.stringify(m.responseText);
} else if ( s.dataType == 'xml' ) {
if ( typeof m.responseXML == 'string' ) {
this.responseXML = parseXML(m.responseXML);
} else {
this.responseXML = m.responseXML;
}
} else {
this.responseText = m.responseText;
}
if( typeof m.status == 'number' || typeof m.status == 'string' ) {
this.status = m.status;
}
if( typeof m.statusText === "string") {
this.statusText = m.statusText;
}
// jQuery < 1.4 doesn't have onreadystate change for xhr
if ( $.isFunction(this.onreadystatechange) ) {
this.onreadystatechange( m.isTimeout ? 'timeout' : undefined );
}
}).apply(that);
};
})(this);
if ( m.proxy ) {
// We're proxying this request and loading in an external file instead
_ajax({
global: false,
url: m.proxy,
type: m.proxyType,
data: m.data,
dataType: s.dataType === "script" ? "text/plain" : s.dataType,
complete: function(xhr, txt) {
m.responseXML = xhr.responseXML;
m.responseText = xhr.responseText;
m.status = xhr.status;
m.statusText = xhr.statusText;
this.responseTimer = setTimeout(process, m.responseTime || 0);
}
});
} else {
// type == 'POST' || 'GET' || 'DELETE'
if ( s.async === false ) {
// TODO: Blocking delay
process();
} else {
this.responseTimer = setTimeout(process, m.responseTime || 50);
}
}
},
abort: function() {
clearTimeout(this.responseTimer);
},
setRequestHeader: function(header, value) {
m.headers[header] = value;
},
getResponseHeader: function(header) {
// 'Last-modified', 'Etag', 'content-type' are all checked by jQuery
if ( m.headers && m.headers[header] ) {
// Return arbitrary headers
return m.headers[header];
} else if ( header.toLowerCase() == 'last-modified' ) {
return m.lastModified || (new Date()).toString();
} else if ( header.toLowerCase() == 'etag' ) {
return m.etag || '';
} else if ( header.toLowerCase() == 'content-type' ) {
return m.contentType || 'text/plain';
}
},
getAllResponseHeaders: function() {
var headers = '';
$.each(m.headers, function(k, v) {
headers += k + ': ' + v + "\n";
});
return headers;
}
};
}
}));
return false;
}
});
// We don't have a mock request, trigger a normal request
if ( !mock ) {
return _ajax.apply($, [origSettings]);
} else {
return mock;
}
}
});
$.mockjaxSettings = {
//url: null,
//type: 'GET',
log: function(msg) {
window['console'] && window.console.log && window.console.log(msg);
},
status: 200,
statusText: "OK",
responseTime: 500,
isTimeout: false,
contentType: 'text/plain',
response: '',
responseText: '',
responseXML: '',
proxy: '',
proxyType: 'GET',
lastModified: null,
etag: '',
headers: {
etag: 'IJF@H#@923uf8023hFO@I#H#',
'content-type' : 'text/plain'
}
};
$.mockjax = function(settings) {
var i = mockHandlers.length;
mockHandlers[i] = settings;
return i;
};
$.mockjaxClear = function(i) {
if ( arguments.length == 1 ) {
mockHandlers[i] = null;
} else {
mockHandlers = [];
}
};
$.mockjax.handler = function(i) {
if ( arguments.length == 1 ) {
return mockHandlers[i];
}
};
})(jQuery);