jquery.mockjax.js 22 KB

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