jquery.mockjax-1.5.3.js 18 KB

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