Subversion-Projekte lars-tiefland.zeldi.de_alt

Revision

Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
2 lars 1
/*!
2
 * MockJax - jQuery Plugin to Mock Ajax requests
3
 *
4
 * Version:  1.5.3
5
 * Released:
6
 * Home:   http://github.com/appendto/jquery-mockjax
7
 * Author:   Jonathan Sharp (http://jdsharp.com)
8
 * License:  MIT,GPL
9
 *
10
 * Copyright (c) 2011 appendTo LLC.
11
 * Dual licensed under the MIT or GPL licenses.
12
 * http://appendto.com/open-source-licenses
13
 */
14
(function($) {
15
	var _ajax = $.ajax,
16
		mockHandlers = [],
17
		mockedAjaxCalls = [],
18
		CALLBACK_REGEX = /=\?(&|$)/,
19
		jsc = (new Date()).getTime();
20
 
21
 
22
	// Parse the given XML string.
23
	function parseXML(xml) {
24
		if ( window.DOMParser == undefined && window.ActiveXObject ) {
25
			DOMParser = function() { };
26
			DOMParser.prototype.parseFromString = function( xmlString ) {
27
				var doc = new ActiveXObject('Microsoft.XMLDOM');
28
				doc.async = 'false';
29
				doc.loadXML( xmlString );
30
				return doc;
31
			};
32
		}
33
 
34
		try {
35
			var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' );
36
			if ( $.isXMLDoc( xmlDoc ) ) {
37
				var err = $('parsererror', xmlDoc);
38
				if ( err.length == 1 ) {
39
					throw('Error: ' + $(xmlDoc).text() );
40
				}
41
			} else {
42
				throw('Unable to parse XML');
43
			}
44
			return xmlDoc;
45
		} catch( e ) {
46
			var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );
47
			$(document).trigger('xmlParseError', [ msg ]);
48
			return undefined;
49
		}
50
	}
51
 
52
	// Trigger a jQuery event
53
	function trigger(s, type, args) {
54
		(s.context ? $(s.context) : $.event).trigger(type, args);
55
	}
56
 
57
	// Check if the data field on the mock handler and the request match. This
58
	// can be used to restrict a mock handler to being used only when a certain
59
	// set of data is passed to it.
60
	function isMockDataEqual( mock, live ) {
61
		var identical = true;
62
		// Test for situations where the data is a querystring (not an object)
63
		if (typeof live === 'string') {
64
			// Querystring may be a regex
65
			return $.isFunction( mock.test ) ? mock.test(live) : mock == live;
66
		}
67
		$.each(mock, function(k) {
68
			if ( live[k] === undefined ) {
69
				identical = false;
70
				return identical;
71
			} else {
72
				// This will allow to compare Arrays
73
				if ( typeof live[k] === 'object' && live[k] !== null ) {
74
					identical = identical && isMockDataEqual(mock[k], live[k]);
75
				} else {
76
					if ( mock[k] && $.isFunction( mock[k].test ) ) {
77
						identical = identical && mock[k].test(live[k]);
78
					} else {
79
						identical = identical && ( mock[k] == live[k] );
80
					}
81
				}
82
			}
83
		});
84
 
85
		return identical;
86
	}
87
 
88
    // See if a mock handler property matches the default settings
89
    function isDefaultSetting(handler, property) {
90
        return handler[property] === $.mockjaxSettings[property];
91
    }
92
 
93
	// Check the given handler should mock the given request
94
	function getMockForRequest( handler, requestSettings ) {
95
		// If the mock was registered with a function, let the function decide if we
96
		// want to mock this request
97
		if ( $.isFunction(handler) ) {
98
			return handler( requestSettings );
99
		}
100
 
101
		// Inspect the URL of the request and check if the mock handler's url
102
		// matches the url for this ajax request
103
		if ( $.isFunction(handler.url.test) ) {
104
			// The user provided a regex for the url, test it
105
			if ( !handler.url.test( requestSettings.url ) ) {
106
				return null;
107
			}
108
		} else {
109
			// Look for a simple wildcard '*' or a direct URL match
110
			var star = handler.url.indexOf('*');
111
			if (handler.url !== requestSettings.url && star === -1 ||
112
					!new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace(/\*/g, '.+')).test(requestSettings.url)) {
113
				return null;
114
			}
115
		}
116
 
117
		// Inspect the data submitted in the request (either POST body or GET query string)
118
		if ( handler.data && requestSettings.data ) {
119
			if ( !isMockDataEqual(handler.data, requestSettings.data) ) {
120
				// They're not identical, do not mock this request
121
				return null;
122
			}
123
		}
124
		// Inspect the request type
125
		if ( handler && handler.type &&
126
				handler.type.toLowerCase() != requestSettings.type.toLowerCase() ) {
127
			// The request type doesn't match (GET vs. POST)
128
			return null;
129
		}
130
 
131
		return handler;
132
	}
133
 
134
	// Process the xhr objects send operation
135
	function _xhrSend(mockHandler, requestSettings, origSettings) {
136
 
137
		// This is a substitute for < 1.4 which lacks $.proxy
138
		var process = (function(that) {
139
			return function() {
140
				return (function() {
141
					var onReady;
142
 
143
					// The request has returned
144
					this.status     = mockHandler.status;
145
					this.statusText = mockHandler.statusText;
146
					this.readyState	= 4;
147
 
148
					// We have an executable function, call it to give
149
					// the mock handler a chance to update it's data
150
					if ( $.isFunction(mockHandler.response) ) {
151
						mockHandler.response(origSettings);
152
					}
153
					// Copy over our mock to our xhr object before passing control back to
154
					// jQuery's onreadystatechange callback
155
					if ( requestSettings.dataType == 'json' && ( typeof mockHandler.responseText == 'object' ) ) {
156
						this.responseText = JSON.stringify(mockHandler.responseText);
157
					} else if ( requestSettings.dataType == 'xml' ) {
158
						if ( typeof mockHandler.responseXML == 'string' ) {
159
							this.responseXML = parseXML(mockHandler.responseXML);
160
							//in jQuery 1.9.1+, responseXML is processed differently and relies on responseText
161
							this.responseText = mockHandler.responseXML;
162
						} else {
163
							this.responseXML = mockHandler.responseXML;
164
						}
165
					} else {
166
						this.responseText = mockHandler.responseText;
167
					}
168
					if( typeof mockHandler.status == 'number' || typeof mockHandler.status == 'string' ) {
169
						this.status = mockHandler.status;
170
					}
171
					if( typeof mockHandler.statusText === "string") {
172
						this.statusText = mockHandler.statusText;
173
					}
174
					// jQuery 2.0 renamed onreadystatechange to onload
175
					onReady = this.onreadystatechange || this.onload;
176
 
177
					// jQuery < 1.4 doesn't have onreadystate change for xhr
178
					if ( $.isFunction( onReady ) ) {
179
						if( mockHandler.isTimeout) {
180
							this.status = -1;
181
						}
182
						onReady.call( this, mockHandler.isTimeout ? 'timeout' : undefined );
183
					} else if ( mockHandler.isTimeout ) {
184
						// Fix for 1.3.2 timeout to keep success from firing.
185
						this.status = -1;
186
					}
187
				}).apply(that);
188
			};
189
		})(this);
190
 
191
		if ( mockHandler.proxy ) {
192
			// We're proxying this request and loading in an external file instead
193
			_ajax({
194
				global: false,
195
				url: mockHandler.proxy,
196
				type: mockHandler.proxyType,
197
				data: mockHandler.data,
198
				dataType: requestSettings.dataType === "script" ? "text/plain" : requestSettings.dataType,
199
				complete: function(xhr) {
200
					mockHandler.responseXML = xhr.responseXML;
201
					mockHandler.responseText = xhr.responseText;
202
                    // Don't override the handler status/statusText if it's specified by the config
203
                    if (isDefaultSetting(mockHandler, 'status')) {
204
					    mockHandler.status = xhr.status;
205
                    }
206
                    if (isDefaultSetting(mockHandler, 'statusText')) {
207
					    mockHandler.statusText = xhr.statusText;
208
                    }
209
 
210
					this.responseTimer = setTimeout(process, mockHandler.responseTime || 0);
211
				}
212
			});
213
		} else {
214
			// type == 'POST' || 'GET' || 'DELETE'
215
			if ( requestSettings.async === false ) {
216
				// TODO: Blocking delay
217
				process();
218
			} else {
219
				this.responseTimer = setTimeout(process, mockHandler.responseTime || 50);
220
			}
221
		}
222
	}
223
 
224
	// Construct a mocked XHR Object
225
	function xhr(mockHandler, requestSettings, origSettings, origHandler) {
226
		// Extend with our default mockjax settings
227
		mockHandler = $.extend(true, {}, $.mockjaxSettings, mockHandler);
228
 
229
		if (typeof mockHandler.headers === 'undefined') {
230
			mockHandler.headers = {};
231
		}
232
		if ( mockHandler.contentType ) {
233
			mockHandler.headers['content-type'] = mockHandler.contentType;
234
		}
235
 
236
		return {
237
			status: mockHandler.status,
238
			statusText: mockHandler.statusText,
239
			readyState: 1,
240
			open: function() { },
241
			send: function() {
242
				origHandler.fired = true;
243
				_xhrSend.call(this, mockHandler, requestSettings, origSettings);
244
			},
245
			abort: function() {
246
				clearTimeout(this.responseTimer);
247
			},
248
			setRequestHeader: function(header, value) {
249
				mockHandler.headers[header] = value;
250
			},
251
			getResponseHeader: function(header) {
252
				// 'Last-modified', 'Etag', 'content-type' are all checked by jQuery
253
				if ( mockHandler.headers && mockHandler.headers[header] ) {
254
					// Return arbitrary headers
255
					return mockHandler.headers[header];
256
				} else if ( header.toLowerCase() == 'last-modified' ) {
257
					return mockHandler.lastModified || (new Date()).toString();
258
				} else if ( header.toLowerCase() == 'etag' ) {
259
					return mockHandler.etag || '';
260
				} else if ( header.toLowerCase() == 'content-type' ) {
261
					return mockHandler.contentType || 'text/plain';
262
				}
263
			},
264
			getAllResponseHeaders: function() {
265
				var headers = '';
266
				$.each(mockHandler.headers, function(k, v) {
267
					headers += k + ': ' + v + "\n";
268
				});
269
				return headers;
270
			}
271
		};
272
	}
273
 
274
	// Process a JSONP mock request.
275
	function processJsonpMock( requestSettings, mockHandler, origSettings ) {
276
		// Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
277
		// because there isn't an easy hook for the cross domain script tag of jsonp
278
 
279
		processJsonpUrl( requestSettings );
280
 
281
		requestSettings.dataType = "json";
282
		if(requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) {
283
			createJsonpCallback(requestSettings, mockHandler, origSettings);
284
 
285
			// We need to make sure
286
			// that a JSONP style response is executed properly
287
 
288
			var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
289
				parts = rurl.exec( requestSettings.url ),
290
				remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
291
 
292
			requestSettings.dataType = "script";
293
			if(requestSettings.type.toUpperCase() === "GET" && remote ) {
294
				var newMockReturn = processJsonpRequest( requestSettings, mockHandler, origSettings );
295
 
296
				// Check if we are supposed to return a Deferred back to the mock call, or just
297
				// signal success
298
				if(newMockReturn) {
299
					return newMockReturn;
300
				} else {
301
					return true;
302
				}
303
			}
304
		}
305
		return null;
306
	}
307
 
308
	// Append the required callback parameter to the end of the request URL, for a JSONP request
309
	function processJsonpUrl( requestSettings ) {
310
		if ( requestSettings.type.toUpperCase() === "GET" ) {
311
			if ( !CALLBACK_REGEX.test( requestSettings.url ) ) {
312
				requestSettings.url += (/\?/.test( requestSettings.url ) ? "&" : "?") +
313
					(requestSettings.jsonp || "callback") + "=?";
314
			}
315
		} else if ( !requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data) ) {
316
			requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?";
317
		}
318
	}
319
 
320
	// Process a JSONP request by evaluating the mocked response text
321
	function processJsonpRequest( requestSettings, mockHandler, origSettings ) {
322
		// Synthesize the mock request for adding a script tag
323
		var callbackContext = origSettings && origSettings.context || requestSettings,
324
			newMock = null;
325
 
326
 
327
		// If the response handler on the moock is a function, call it
328
		if ( mockHandler.response && $.isFunction(mockHandler.response) ) {
329
			mockHandler.response(origSettings);
330
		} else {
331
 
332
			// Evaluate the responseText javascript in a global context
333
			if( typeof mockHandler.responseText === 'object' ) {
334
				$.globalEval( '(' + JSON.stringify( mockHandler.responseText ) + ')');
335
			} else {
336
				$.globalEval( '(' + mockHandler.responseText + ')');
337
			}
338
		}
339
 
340
		// Successful response
341
		jsonpSuccess( requestSettings, callbackContext, mockHandler );
342
		jsonpComplete( requestSettings, callbackContext, mockHandler );
343
 
344
		// If we are running under jQuery 1.5+, return a deferred object
345
		if($.Deferred){
346
			newMock = new $.Deferred();
347
			if(typeof mockHandler.responseText == "object"){
348
				newMock.resolveWith( callbackContext, [mockHandler.responseText] );
349
			}
350
			else{
351
				newMock.resolveWith( callbackContext, [$.parseJSON( mockHandler.responseText )] );
352
			}
353
		}
354
		return newMock;
355
	}
356
 
357
 
358
	// Create the required JSONP callback function for the request
359
	function createJsonpCallback( requestSettings, mockHandler, origSettings ) {
360
		var callbackContext = origSettings && origSettings.context || requestSettings;
361
		var jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++);
362
 
363
		// Replace the =? sequence both in the query string and the data
364
		if ( requestSettings.data ) {
365
			requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1");
366
		}
367
 
368
		requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1");
369
 
370
 
371
		// Handle JSONP-style loading
372
		window[ jsonp ] = window[ jsonp ] || function( tmp ) {
373
			data = tmp;
374
			jsonpSuccess( requestSettings, callbackContext, mockHandler );
375
			jsonpComplete( requestSettings, callbackContext, mockHandler );
376
			// Garbage collect
377
			window[ jsonp ] = undefined;
378
 
379
			try {
380
				delete window[ jsonp ];
381
			} catch(e) {}
382
 
383
			if ( head ) {
384
				head.removeChild( script );
385
			}
386
		};
387
	}
388
 
389
	// The JSONP request was successful
390
	function jsonpSuccess(requestSettings, callbackContext, mockHandler) {
391
		// If a local callback was specified, fire it and pass it the data
392
		if ( requestSettings.success ) {
393
			requestSettings.success.call( callbackContext, mockHandler.responseText || "", status, {} );
394
		}
395
 
396
		// Fire the global callback
397
		if ( requestSettings.global ) {
398
			trigger(requestSettings, "ajaxSuccess", [{}, requestSettings] );
399
		}
400
	}
401
 
402
	// The JSONP request was completed
403
	function jsonpComplete(requestSettings, callbackContext) {
404
		// Process result
405
		if ( requestSettings.complete ) {
406
			requestSettings.complete.call( callbackContext, {} , status );
407
		}
408
 
409
		// The request was completed
410
		if ( requestSettings.global ) {
411
			trigger( "ajaxComplete", [{}, requestSettings] );
412
		}
413
 
414
		// Handle the global AJAX counter
415
		if ( requestSettings.global && ! --$.active ) {
416
			$.event.trigger( "ajaxStop" );
417
		}
418
	}
419
 
420
 
421
	// The core $.ajax replacement.
422
	function handleAjax( url, origSettings ) {
423
		var mockRequest, requestSettings, mockHandler;
424
 
425
		// If url is an object, simulate pre-1.5 signature
426
		if ( typeof url === "object" ) {
427
			origSettings = url;
428
			url = undefined;
429
		} else {
430
			// work around to support 1.5 signature
431
			origSettings.url = url;
432
		}
433
 
434
		// Extend the original settings for the request
435
		requestSettings = $.extend(true, {}, $.ajaxSettings, origSettings);
436
 
437
		// Iterate over our mock handlers (in registration order) until we find
438
		// one that is willing to intercept the request
439
		for(var k = 0; k < mockHandlers.length; k++) {
440
			if ( !mockHandlers[k] ) {
441
				continue;
442
			}
443
 
444
			mockHandler = getMockForRequest( mockHandlers[k], requestSettings );
445
			if(!mockHandler) {
446
				// No valid mock found for this request
447
				continue;
448
			}
449
 
450
			mockedAjaxCalls.push(requestSettings);
451
 
452
			// If logging is enabled, log the mock to the console
453
			$.mockjaxSettings.log( mockHandler, requestSettings );
454
 
455
 
456
			if ( requestSettings.dataType === "jsonp" ) {
457
				if ((mockRequest = processJsonpMock( requestSettings, mockHandler, origSettings ))) {
458
					// This mock will handle the JSONP request
459
					return mockRequest;
460
				}
461
			}
462
 
463
 
464
			// Removed to fix #54 - keep the mocking data object intact
465
			//mockHandler.data = requestSettings.data;
466
 
467
			mockHandler.cache = requestSettings.cache;
468
			mockHandler.timeout = requestSettings.timeout;
469
			mockHandler.global = requestSettings.global;
470
 
471
			copyUrlParameters(mockHandler, origSettings);
472
 
473
			(function(mockHandler, requestSettings, origSettings, origHandler) {
474
				mockRequest = _ajax.call($, $.extend(true, {}, origSettings, {
475
					// Mock the XHR object
476
					xhr: function() { return xhr( mockHandler, requestSettings, origSettings, origHandler ); }
477
				}));
478
			})(mockHandler, requestSettings, origSettings, mockHandlers[k]);
479
 
480
			return mockRequest;
481
		}
482
 
483
		// We don't have a mock request
484
		if($.mockjaxSettings.throwUnmocked === true) {
485
			throw('AJAX not mocked: ' + origSettings.url);
486
		}
487
		else { // trigger a normal request
488
			return _ajax.apply($, [origSettings]);
489
		}
490
	}
491
 
492
	/**
493
	* Copies URL parameter values if they were captured by a regular expression
494
	* @param {Object} mockHandler
495
	* @param {Object} origSettings
496
	*/
497
	function copyUrlParameters(mockHandler, origSettings) {
498
		//parameters aren't captured if the URL isn't a RegExp
499
		if (!(mockHandler.url instanceof RegExp)) {
500
			return;
501
		}
502
		//if no URL params were defined on the handler, don't attempt a capture
503
		if (!mockHandler.hasOwnProperty('urlParams')) {
504
			return;
505
		}
506
		var captures = mockHandler.url.exec(origSettings.url);
507
		//the whole RegExp match is always the first value in the capture results
508
		if (captures.length === 1) {
509
			return;
510
		}
511
		captures.shift();
512
		//use handler params as keys and capture resuts as values
513
		var i = 0,
514
		capturesLength = captures.length,
515
		paramsLength = mockHandler.urlParams.length,
516
		//in case the number of params specified is less than actual captures
517
		maxIterations = Math.min(capturesLength, paramsLength),
518
		paramValues = {};
519
		for (i; i < maxIterations; i++) {
520
			var key = mockHandler.urlParams[i];
521
			paramValues[key] = captures[i];
522
		}
523
		origSettings.urlParams = paramValues;
524
	}
525
 
526
 
527
	// Public
528
 
529
	$.extend({
530
		ajax: handleAjax
531
	});
532
 
533
	$.mockjaxSettings = {
534
		//url:        null,
535
		//type:       'GET',
536
		log:          function( mockHandler, requestSettings ) {
537
			if ( mockHandler.logging === false ||
538
				 ( typeof mockHandler.logging === 'undefined' && $.mockjaxSettings.logging === false ) ) {
539
				return;
540
			}
541
			if ( window.console && console.log ) {
542
				var message = 'MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url;
543
				var request = $.extend({}, requestSettings);
544
 
545
				if (typeof console.log === 'function') {
546
					console.log(message, request);
547
				} else {
548
					try {
549
						console.log( message + ' ' + JSON.stringify(request) );
550
					} catch (e) {
551
						console.log(message);
552
					}
553
				}
554
			}
555
		},
556
		logging:       true,
557
		status:        200,
558
		statusText:    "OK",
559
		responseTime:  500,
560
		isTimeout:     false,
561
		throwUnmocked: false,
562
		contentType:   'text/plain',
563
		response:      '',
564
		responseText:  '',
565
		responseXML:   '',
566
		proxy:         '',
567
		proxyType:     'GET',
568
 
569
		lastModified:  null,
570
		etag:          '',
571
		headers: {
572
			etag: 'IJF@H#@923uf8023hFO@I#H#',
573
			'content-type' : 'text/plain'
574
		}
575
	};
576
 
577
	$.mockjax = function(settings) {
578
		var i = mockHandlers.length;
579
		mockHandlers[i] = settings;
580
		return i;
581
	};
582
	$.mockjaxClear = function(i) {
583
		if ( arguments.length == 1 ) {
584
			mockHandlers[i] = null;
585
		} else {
586
			mockHandlers = [];
587
		}
588
		mockedAjaxCalls = [];
589
	};
590
	$.mockjax.handler = function(i) {
591
		if ( arguments.length == 1 ) {
592
			return mockHandlers[i];
593
		}
594
	};
595
	$.mockjax.mockedAjaxCalls = function() {
596
		return mockedAjaxCalls;
597
	};
598
})(jQuery);