Socket
Socket
Sign inDemoInstall

jquery-mockjax

Package Overview
Dependencies
1
Maintainers
3
Versions
15
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 2.1.1 to 2.2.0

lib/jquery-1.12.4.js

4

bower.json
{
"name": "jquery-mockjax",
"main": ["dist/jquery.mockjax.js"],
"main": "dist/jquery.mockjax.js",
"dependencies": {
"jquery": "~2.1.3"
"jquery": ">=1.5.0"
},

@@ -7,0 +7,0 @@ "ignore": [

@@ -0,1 +1,11 @@

## 2016-06-08 v2.2.0
* Fix bower dependency on jQuery to allow any supported version
* Allow developer to indicate that ajax calls should _not_ be retained (thanks @suchipi)
* Fix to allow responseTime to work with deferred jsonp
* Updated to test on latest jQuery versions
* Added JSDoc3 blocks to public API methods
* Refactored logging: now has levels, easier to overwrite, more messages
* Added ability for `data` matching to be a function (thanks @koorgoo)
* Added ability to pass in array of mocks in addition to singles (thanks again @koorgoo)
## 2016-02-07 v2.1.1

@@ -2,0 +12,0 @@ * Reorganize test cases into separate files for ease of maintenance and testing

/*! jQuery Mockjax
* A Plugin providing simple and flexible mocking of ajax requests and responses
*
* Version: 2.1.1
* Version: 2.2.0
* Home: https://github.com/jakerella/jquery-mockjax

@@ -42,5 +42,5 @@ * Copyright (c) 2016 Jordan Kasper, formerly appendTo;

CALLBACK_REGEX = /=\?(&|$)/,
jsc = (new Date()).getTime();
jsc = (new Date()).getTime(),
DEFAULT_RESPONSE_TIME = 500;
// Parse the given XML string.

@@ -80,3 +80,9 @@ function parseXML(xml) {

function isMockDataEqual( mock, live ) {
logger.debug( mock, ['Checking mock data against request data', mock, live] );
var identical = true;
if ( $.isFunction(mock) ) {
return !!mock(live);
}
// Test for situations where the data is a querystring (not an object)

@@ -93,3 +99,3 @@ if (typeof live === 'string') {

}
$.each(mock, function(k) {

@@ -117,3 +123,3 @@ if ( live[k] === undefined ) {

}
function getQueryParams(queryString) {

@@ -123,3 +129,3 @@ var i, l, param, tmp,

params = String(queryString).split(/&/);
for (i=0, l=params.length; i<l; ++i) {

@@ -134,3 +140,3 @@ param = params[i];

}
if (paramsObj[param[0]]) {

@@ -149,3 +155,5 @@ // this is an array query param (more than one entry in query)

}
logger.debug( null, ['Getting query params from string', queryString, paramsObj] );
return paramsObj;

@@ -249,2 +257,3 @@ }

function _xhrSend(mockHandler, requestSettings, origSettings) {
logger.debug( mockHandler, ['Sending fake XHR request', mockHandler, requestSettings, origSettings] );

@@ -324,2 +333,3 @@ // This is a substitute for < 1.4 which lacks $.proxy

if ( mockHandler.proxy ) {
logger.info( mockHandler, ['Retrieving proxy file: ' + mockHandler.proxy, mockHandler] );
// We're proxying this request and loading in an external file instead

@@ -338,3 +348,3 @@ _ajax({

mockHandler.responseXML = mockHandler.responseText = xhr.responseText;
// Don't override the handler status/statusText if it's specified by the config

@@ -370,2 +380,4 @@ if (isDefaultSetting(mockHandler, 'status')) {

function xhr(mockHandler, requestSettings, origSettings, origHandler) {
logger.debug( mockHandler, ['Creating new mock XHR object', mockHandler, requestSettings, origSettings, origHandler] );
// Extend with our default mockjax settings

@@ -474,2 +486,4 @@ mockHandler = $.extend(true, {}, $.mockjaxSettings, mockHandler);

function processJsonpRequest( requestSettings, mockHandler, origSettings ) {
logger.debug( mockHandler, ['Performing JSONP request', mockHandler, requestSettings, origSettings] );
// Synthesize the mock request for adding a script tag

@@ -491,2 +505,3 @@ var callbackContext = origSettings && origSettings.context || requestSettings,

} else if (mockHandler.proxy) {
logger.info( mockHandler, ['Performing JSONP proxy request: ' + mockHandler.proxy, mockHandler] );

@@ -510,4 +525,4 @@ // This handles the unique case where we have a remote URL, but want to proxy the JSONP

} else {
$.globalEval( '(' +
((typeof mockHandler.responseText === 'string') ?
$.globalEval( '(' +
((typeof mockHandler.responseText === 'string') ?
('"' + mockHandler.responseText + '"') : mockHandler.responseText) +

@@ -529,11 +544,12 @@ ')');

jsonpComplete( requestSettings, callbackContext );
}, parseResponseTimeOpt( mockHandler.responseTime ));
if ( newMock ) {
try {
json = $.parseJSON( mockHandler.responseText );
} catch (err) { /* just checking... */ }
if ( newMock ) {
try {
json = $.parseJSON( mockHandler.responseText );
} catch (err) { /* just checking... */ }
newMock.resolveWith( callbackContext, [json || mockHandler.responseText] );
}
newMock.resolveWith( callbackContext, [json || mockHandler.responseText] );
logger.log( mockHandler, ['JSONP mock call complete', mockHandler, newMock] );
}
}, parseResponseTimeOpt( mockHandler.responseTime ));
}

@@ -607,2 +623,4 @@

logger.debug( null, ['Ajax call intercepted', url, origSettings] );
// If url is an object, simulate pre-1.5 signature

@@ -643,2 +661,3 @@ if ( typeof url === 'object' ) {

if(!mockHandler) {
logger.debug( mockHandlers[k], ['Mock does not match request', url, requestSettings] );
// No valid mock found for this request

@@ -648,6 +667,11 @@ continue;

mockedAjaxCalls.push(requestSettings);
if ($.mockjaxSettings.retainAjaxCalls) {
mockedAjaxCalls.push(requestSettings);
}
// If logging is enabled, log the mock to the console
$.mockjaxSettings.log( mockHandler, requestSettings );
logger.info( mockHandler, [
'MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url,
$.ajaxSetup({}, requestSettings)
] );

@@ -662,7 +686,7 @@

// We are mocking, so there will be no cross domain request, however, jQuery
// aggressively pursues this if the domains don't match, so we need to
// explicitly disallow it. (See #136)
origSettings.crossDomain = false;
// We are mocking, so there will be no cross domain request, however, jQuery
// aggressively pursues this if the domains don't match, so we need to
// explicitly disallow it. (See #136)
origSettings.crossDomain = false;
// Removed to fix #54 - keep the mocking data object intact

@@ -714,3 +738,6 @@ //mockHandler.data = requestSettings.data;

// We don't have a mock request
unmockedAjaxCalls.push(origSettings);
logger.log( null, ['No mock matched to request', url, origSettings] );
if ($.mockjaxSettings.retainAjaxCalls) {
unmockedAjaxCalls.push(origSettings);
}
if($.mockjaxSettings.throwUnmocked === true) {

@@ -774,2 +801,7 @@ throw new Error('AJAX not mocked: ' + origSettings.url);

results.push(handler);
} else {
logger.log( handler, [
'Clearing mock: ' + (handler && handler.url),
handler
] );
}

@@ -787,55 +819,127 @@ }

var DEFAULT_RESPONSE_TIME = 500;
var logger = {
_log: function logger( mockHandler, args, level ) {
var loggerLevel = $.mockjaxSettings.logging;
if (mockHandler && typeof mockHandler.logging !== 'undefined') {
loggerLevel = mockHandler.logging;
}
level = ( level === 0 ) ? level : ( level || logLevels.LOG );
args = (args.splice) ? args : [ args ];
$.mockjaxSettings = {
//url: null,
//type: 'GET',
log: function( mockHandler, requestSettings ) {
if ( mockHandler.logging === false ||
( typeof mockHandler.logging === 'undefined' && $.mockjaxSettings.logging === false ) ) {
// Is logging turned off for this mock or mockjax as a whole?
// Or is this log message above the desired log level?
if ( loggerLevel === false || loggerLevel < level ) {
return;
}
if ( window.console && console.log ) {
var message = 'MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url;
var request = $.ajaxSetup({}, requestSettings);
if (typeof console.log === 'function') {
console.log(message, request);
} else {
try {
console.log( message + ' ' + JSON.stringify(request) );
} catch (e) {
console.log(message);
}
}
if ( $.mockjaxSettings.log ) {
return $.mockjaxSettings.log( mockHandler, args[1] || args[0] );
} else if ( $.mockjaxSettings.logger && $.mockjaxSettings.logger[$.mockjaxSettings.logLevelMethods[level]] ) {
return $.mockjaxSettings.logger[$.mockjaxSettings.logLevelMethods[level]].apply( $.mockjaxSettings.logger, args );
}
},
logging: true,
namespace: null,
status: 200,
statusText: 'OK',
responseTime: DEFAULT_RESPONSE_TIME,
isTimeout: false,
throwUnmocked: false,
contentType: 'text/plain',
response: '',
responseText: '',
responseXML: '',
proxy: '',
proxyType: 'GET',
/**
* Convenience method for logging a DEBUG level message
* @param {Object} m The mock handler in question
* @param {Array|String|Object} a The items to log
* @return {?} Will return whatever the $.mockjaxSettings.logger method for this level would return (generally 'undefined')
*/
debug: function(m,a) { return logger._log(m,a,logLevels.DEBUG); },
/**
* @see logger.debug
*/
log: function(m,a) { return logger._log(m,a,logLevels.LOG); },
/**
* @see logger.debug
*/
info: function(m,a) { return logger._log(m,a,logLevels.INFO); },
/**
* @see logger.debug
*/
warn: function(m,a) { return logger._log(m,a,logLevels.WARN); },
/**
* @see logger.debug
*/
error: function(m,a) { return logger._log(m,a,logLevels.ERROR); }
};
lastModified: null,
etag: '',
headers: {
etag: 'IJF@H#@923uf8023hFO@I#H#',
'content-type' : 'text/plain'
}
var logLevels = {
DEBUG: 4,
LOG: 3,
INFO: 2,
WARN: 1,
ERROR: 0
};
/**
* Default settings for mockjax. Some of these are used for defaults of
* individual mock handlers, and some are for the library as a whole.
* For individual mock handler settings, please see the README on the repo:
* https://github.com/jakerella/jquery-mockjax#api-methods
*
* @type {Object}
*/
$.mockjaxSettings = {
log: null, // this is only here for historical purposes... use $.mockjaxSettings.logger
logger: window.console,
logging: 2,
logLevelMethods: ['error', 'warn', 'info', 'log', 'debug'],
namespace: null,
status: 200,
statusText: 'OK',
responseTime: DEFAULT_RESPONSE_TIME,
isTimeout: false,
throwUnmocked: false,
retainAjaxCalls: true,
contentType: 'text/plain',
response: '',
responseText: '',
responseXML: '',
proxy: '',
proxyType: 'GET',
lastModified: null,
etag: '',
headers: {
etag: 'IJF@H#@923uf8023hFO@I#H#',
'content-type' : 'text/plain'
}
};
/**
* Create a new mock Ajax handler. When a mock handler is matched during a
* $.ajax() call this library will intercept that request and fake a response
* using the data and methods in the mock. You can see all settings in the
* README of the main repository:
* https://github.com/jakerella/jquery-mockjax#api-methods
*
* @param {Object} settings The mock handelr settings: https://github.com/jakerella/jquery-mockjax#api-methods
* @return {Number} The id (index) of the mock handler suitable for clearing (see $.mockjax.clear())
*/
$.mockjax = function(settings) {
// Multiple mocks.
if ( $.isArray(settings) ) {
return $.map(settings, function(s) {
return $.mockjax(s);
});
}
var i = mockHandlers.length;
mockHandlers[i] = settings;
logger.log( settings, ['Created new mock handler', settings] );
return i;
};
$.mockjax._logger = logger;
/**
* Remove an Ajax mock from those held in memory. This will prevent any
* future Ajax request mocking for matched requests.
* NOTE: Clearing a mock will not prevent the resolution of in progress requests
*
* @param {Number|String|RegExp} i OPTIONAL The mock to clear. If not provided, all mocks are cleared,
* if a number it is the index in the in-memory cache. If a string or
* RegExp, find a mock that matches that URL and clear it.
* @return {void}
*/
$.mockjax.clear = function(i) {

@@ -845,4 +949,9 @@ if ( typeof i === 'string' || i instanceof RegExp) {

} else if ( i || i === 0 ) {
logger.log( mockHandlers[i], [
'Clearing mock: ' + (mockHandlers[i] && mockHandlers[i].url),
mockHandlers[i]
] );
mockHandlers[i] = null;
} else {
logger.log( null, 'Clearing all mocks' );
mockHandlers = [];

@@ -853,2 +962,22 @@ }

};
/**
* By default all Ajax requests performed after loading Mockjax are recorded
* so that we can see which requests were mocked and which were not. This
* method allows the developer to clear those retained requests.
*
* @return {void}
*/
$.mockjax.clearRetainedAjaxCalls = function() {
mockedAjaxCalls = [];
unmockedAjaxCalls = [];
logger.debug( null, 'Cleared retained ajax calls' );
};
/**
* Retrive the mock handler with the given id (index).
*
* @param {Number} i The id (index) to retrieve
* @return {Object} The mock handler settings
*/
$.mockjax.handler = function(i) {

@@ -859,5 +988,18 @@ if ( arguments.length === 1 ) {

};
/**
* Retrieve all Ajax calls that have been mocked by this library during the
* current session (in other words, only since you last loaded this file).
*
* @return {Array} The mocked Ajax calls (request settings)
*/
$.mockjax.mockedAjaxCalls = function() {
return mockedAjaxCalls;
};
/**
* Return all mock handlers that have NOT been matched against Ajax requests
*
* @return {Array} The mock handlers
*/
$.mockjax.unfiredHandlers = function() {

@@ -873,2 +1015,9 @@ var results = [];

};
/**
* Retrieve all Ajax calls that have NOT been mocked by this library during
* the current session (in other words, only since you last loaded this file).
*
* @return {Array} The mocked Ajax calls (request settings)
*/
$.mockjax.unmockedAjaxCalls = function() {

@@ -875,0 +1024,0 @@ return unmockedAjaxCalls;

/*! jQuery Mockjax
* A Plugin providing simple and flexible mocking of ajax requests and responses
*
* Version: 2.1.1
* Version: 2.2.0
* Home: https://github.com/jakerella/jquery-mockjax

@@ -12,2 +12,2 @@ * Copyright (c) 2016 Jordan Kasper, formerly appendTo;

*/
!function(a,b){"use strict";if("function"==typeof define&&define.amd&&define.amd.jQuery)define(["jquery"],function(c){return b(c,a)});else{if("object"!=typeof exports)return b(a.jQuery||a.$,a);module.exports=b}}(this,function(a,b){"use strict";function c(c){void 0===b.DOMParser&&b.ActiveXObject&&(b.DOMParser=function(){},DOMParser.prototype.parseFromString=function(a){var b=new ActiveXObject("Microsoft.XMLDOM");return b.async="false",b.loadXML(a),b});try{var d=(new DOMParser).parseFromString(c,"text/xml");if(!a.isXMLDoc(d))throw new Error("Unable to parse XML");var e=a("parsererror",d);if(1===e.length)throw new Error("Error: "+a(d).text());return d}catch(f){var g=void 0===f.name?f:f.name+": "+f.message;return void a(document).trigger("xmlParseError",[g])}}function d(b,c){var f=!0;if("string"==typeof c){if(a.isFunction(b.test))return b.test(c);if("object"!=typeof b)return b===c;c=e(c)}return a.each(b,function(e){return void 0===c[e]?f=!1:void("object"==typeof c[e]&&null!==c[e]?(f&&a.isArray(c[e])&&(f=a.isArray(b[e])&&c[e].length===b[e].length),f=f&&d(b[e],c[e])):f=b[e]&&a.isFunction(b[e].test)?f&&b[e].test(c[e]):f&&b[e]===c[e])}),f}function e(a){var b,c,d,e,f={},g=String(a).split(/&/);for(b=0,c=g.length;c>b;++b){d=g[b];try{d=decodeURIComponent(d.replace(/\+/g," ")),d=d.split(/=/)}catch(h){continue}f[d[0]]?(f[d[0]].splice||(e=f[d[0]],f[d[0]]=[],f[d[0]].push(e)),f[d[0]].push(d[1])):f[d[0]]=d[1]}return f}function f(b,c){return b[c]===a.mockjaxSettings[c]}function g(b,c){if(a.isFunction(b))return b(c);if(a.isFunction(b.url.test)){if(!b.url.test(c.url))return null}else{var e=b.namespace||a.mockjaxSettings.namespace;if(e){var f=[e,b.url].join("/");f=f.replace(/(\/+)/g,"/"),b.url=f}var g=b.url.indexOf("*");if(b.url!==c.url&&-1===g||!new RegExp(b.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g,"\\$&").replace(/\*/g,".+")).test(c.url))return null}if(b.requestHeaders){if(void 0===c.headers)return null;var h=!1;if(a.each(b.requestHeaders,function(a,b){var d=c.headers[a];return d!==b?(h=!0,!1):void 0}),h)return null}return!b.data||c.data&&d(b.data,c.data)?b&&b.type&&b.type.toLowerCase()!==c.type.toLowerCase()?null:b:null}function h(a){return"number"==typeof a&&a>=0}function i(b){if(a.isArray(b)&&2===b.length){var c=b[0],d=b[1];if(h(c)&&h(d))return Math.floor(Math.random()*(d-c))+c}else if(h(b))return b;return B}function j(b,d,e){var g=function(f){return function(){return function(){this.status=b.status,this.statusText=b.statusText,this.readyState=1;var g=function(){this.readyState=4;var e;"json"===d.dataType&&"object"==typeof b.responseText?this.responseText=JSON.stringify(b.responseText):"xml"===d.dataType?"string"==typeof b.responseXML?(this.responseXML=c(b.responseXML),this.responseText=b.responseXML):this.responseXML=b.responseXML:"object"==typeof b.responseText&&null!==b.responseText?(b.contentType="application/json",this.responseText=JSON.stringify(b.responseText)):this.responseText=b.responseText,("number"==typeof b.status||"string"==typeof b.status)&&(this.status=b.status),"string"==typeof b.statusText&&(this.statusText=b.statusText),e=this.onload||this.onreadystatechange,a.isFunction(e)?(b.isTimeout&&(this.status=-1),e.call(this,b.isTimeout?"timeout":void 0)):b.isTimeout&&(this.status=-1)};if(a.isFunction(b.response)){if(2===b.response.length)return void b.response(e,function(){g.call(f)});b.response(e)}g.call(f)}.apply(f)}}(this);b.proxy?v({global:!1,url:b.proxy,type:b.proxyType,data:b.data,async:d.async,dataType:"script"===d.dataType?"text/plain":d.dataType,complete:function(a){b.responseXML=b.responseText=a.responseText,f(b,"status")&&(b.status=a.status),f(b,"statusText")&&(b.statusText=a.statusText),d.async===!1?g():this.responseTimer=setTimeout(g,i(b.responseTime))}}):d.async===!1?g():this.responseTimer=setTimeout(g,i(b.responseTime))}function k(b,c,d,e){return b=a.extend(!0,{},a.mockjaxSettings,b),"undefined"==typeof b.headers&&(b.headers={}),"undefined"==typeof c.headers&&(c.headers={}),b.contentType&&(b.headers["content-type"]=b.contentType),{status:b.status,statusText:b.statusText,readyState:1,open:function(){},send:function(){e.fired=!0,j.call(this,b,c,d)},abort:function(){clearTimeout(this.responseTimer)},setRequestHeader:function(a,b){c.headers[a]=b},getResponseHeader:function(a){return b.headers&&b.headers[a]?b.headers[a]:"last-modified"===a.toLowerCase()?b.lastModified||(new Date).toString():"etag"===a.toLowerCase()?b.etag||"":"content-type"===a.toLowerCase()?b.contentType||"text/plain":void 0},getAllResponseHeaders:function(){var c="";return b.contentType&&(b.headers["Content-Type"]=b.contentType),a.each(b.headers,function(a,b){c+=a+": "+b+"\n"}),c}}}function l(a,b,c){if(m(a),a.dataType="json",a.data&&z.test(a.data)||z.test(a.url)){p(a,b,c);var d=/^(\w+:)?\/\/([^\/?#]+)/,e=d.exec(a.url),f=e&&(e[1]&&e[1]!==location.protocol||e[2]!==location.host);if(a.dataType="script","GET"===a.type.toUpperCase()&&f){var g=n(a,b,c);return g?g:!0}}return null}function m(a){"GET"===a.type.toUpperCase()?z.test(a.url)||(a.url+=(/\?/.test(a.url)?"&":"?")+(a.jsonp||"callback")+"=?"):a.data&&z.test(a.data)||(a.data=(a.data?a.data+"&":"")+(a.jsonp||"callback")+"=?")}function n(b,c,d){var e=d&&d.context||b,f=a.Deferred?new a.Deferred:null;if(c.response&&a.isFunction(c.response))c.response(d);else if("object"==typeof c.responseText)a.globalEval("("+JSON.stringify(c.responseText)+")");else{if(c.proxy)return v({global:!1,url:c.proxy,type:c.proxyType,data:c.data,dataType:"script"===b.dataType?"text/plain":b.dataType,complete:function(d){a.globalEval("("+d.responseText+")"),o(b,c,e,f)}}),f;a.globalEval("("+("string"==typeof c.responseText?'"'+c.responseText+'"':c.responseText)+")")}return o(b,c,e,f),f}function o(b,c,d,e){var f;if(setTimeout(function(){q(b,d,c),r(b,d)},i(c.responseTime)),e){try{f=a.parseJSON(c.responseText)}catch(g){}e.resolveWith(d,[f||c.responseText])}}function p(a,c,d){var e=d&&d.context||a,f="string"==typeof a.jsonpCallback&&a.jsonpCallback||"jsonp"+A++;a.data&&(a.data=(a.data+"").replace(z,"="+f+"$1")),a.url=a.url.replace(z,"="+f+"$1"),b[f]=b[f]||function(){q(a,e,c),r(a,e),b[f]=void 0;try{delete b[f]}catch(d){}},a.jsonpCallback=f}function q(b,c,d){b.success&&b.success.call(c,d.responseText||"","success",{}),b.global&&(b.context?a(b.context):a.event).trigger("ajaxSuccess",[{},b])}function r(b,c){b.complete&&b.complete.call(c,{statusText:"success",status:200},"success"),b.global&&(b.context?a(b.context):a.event).trigger("ajaxComplete",[{},b]),b.global&&!--a.active&&a.event.trigger("ajaxStop")}function s(b,c){var d,e,f,h;"object"==typeof b?(c=b,b=void 0):(c=c||{},c.url=b||c.url),e=a.ajaxSetup({},c),e.type=e.method=e.method||e.type,h=function(b,d){var e=c[b.toLowerCase()];return function(){a.isFunction(e)&&e.apply(this,[].slice.call(arguments)),d["onAfter"+b]()}};for(var i=0;i<w.length;i++)if(w[i]&&(f=g(w[i],e)))return x.push(e),a.mockjaxSettings.log(f,e),e.dataType&&"JSONP"===e.dataType.toUpperCase()&&(d=l(e,f,c))?d:(c.crossDomain=!1,f.cache=e.cache,f.timeout=e.timeout,f.global=e.global,f.isTimeout&&(f.responseTime>1?c.timeout=f.responseTime-1:(f.responseTime=2,c.timeout=1)),a.isFunction(f.onAfterSuccess)&&(c.success=h("Success",f)),a.isFunction(f.onAfterError)&&(c.error=h("Error",f)),a.isFunction(f.onAfterComplete)&&(c.complete=h("Complete",f)),t(f,c),function(b,c,e,f){d=v.call(a,a.extend(!0,{},e,{xhr:function(){return k(b,c,e,f)}}))}(f,e,c,w[i]),d);if(y.push(c),a.mockjaxSettings.throwUnmocked===!0)throw new Error("AJAX not mocked: "+c.url);return v.apply(a,[c])}function t(a,b){if(a.url instanceof RegExp&&a.hasOwnProperty("urlParams")){var c=a.url.exec(b.url);if(1!==c.length){c.shift();var d=0,e=c.length,f=a.urlParams.length,g=Math.min(e,f),h={};for(d;g>d;d++){var i=a.urlParams[d];h[i]=c[d]}b.urlParams=h}}}function u(a){var b,c,d,e=[],f=a instanceof RegExp?function(b){return a.test(b)}:function(b){return a===b};for(b=0,c=w.length;c>b;b++)d=w[b],f(d.url)||e.push(d);return e}var v=a.ajax,w=[],x=[],y=[],z=/=\?(&|$)/,A=(new Date).getTime();a.extend({ajax:s});var B=500;return a.mockjaxSettings={log:function(c,d){if(c.logging!==!1&&("undefined"!=typeof c.logging||a.mockjaxSettings.logging!==!1)&&b.console&&console.log){var e="MOCK "+d.type.toUpperCase()+": "+d.url,f=a.ajaxSetup({},d);if("function"==typeof console.log)console.log(e,f);else try{console.log(e+" "+JSON.stringify(f))}catch(g){console.log(e)}}},logging:!0,namespace:null,status:200,statusText:"OK",responseTime:B,isTimeout:!1,throwUnmocked:!1,contentType:"text/plain",response:"",responseText:"",responseXML:"",proxy:"",proxyType:"GET",lastModified:null,etag:"",headers:{etag:"IJF@H#@923uf8023hFO@I#H#","content-type":"text/plain"}},a.mockjax=function(a){var b=w.length;return w[b]=a,b},a.mockjax.clear=function(a){"string"==typeof a||a instanceof RegExp?w=u(a):a||0===a?w[a]=null:w=[],x=[],y=[]},a.mockjax.handler=function(a){return 1===arguments.length?w[a]:void 0},a.mockjax.mockedAjaxCalls=function(){return x},a.mockjax.unfiredHandlers=function(){for(var a=[],b=0,c=w.length;c>b;b++){var d=w[b];null===d||d.fired||a.push(d)}return a},a.mockjax.unmockedAjaxCalls=function(){return y},a.mockjax});
!function(a,b){"use strict";if("function"==typeof define&&define.amd&&define.amd.jQuery)define(["jquery"],function(c){return b(c,a)});else{if("object"!=typeof exports)return b(a.jQuery||a.$,a);module.exports=b}}(this,function(a,b){"use strict";function c(c){void 0===b.DOMParser&&b.ActiveXObject&&(b.DOMParser=function(){},DOMParser.prototype.parseFromString=function(a){var b=new ActiveXObject("Microsoft.XMLDOM");return b.async="false",b.loadXML(a),b});try{var d=(new DOMParser).parseFromString(c,"text/xml");if(!a.isXMLDoc(d))throw new Error("Unable to parse XML");var e=a("parsererror",d);if(1===e.length)throw new Error("Error: "+a(d).text());return d}catch(f){var g=void 0===f.name?f:f.name+": "+f.message;return void a(document).trigger("xmlParseError",[g])}}function d(b,c){C.debug(b,["Checking mock data against request data",b,c]);var f=!0;if(a.isFunction(b))return!!b(c);if("string"==typeof c){if(a.isFunction(b.test))return b.test(c);if("object"!=typeof b)return b===c;c=e(c)}return a.each(b,function(e){return void 0===c[e]?f=!1:void("object"==typeof c[e]&&null!==c[e]?(f&&a.isArray(c[e])&&(f=a.isArray(b[e])&&c[e].length===b[e].length),f=f&&d(b[e],c[e])):f=b[e]&&a.isFunction(b[e].test)?f&&b[e].test(c[e]):f&&b[e]===c[e])}),f}function e(a){var b,c,d,e,f={},g=String(a).split(/&/);for(b=0,c=g.length;c>b;++b){d=g[b];try{d=decodeURIComponent(d.replace(/\+/g," ")),d=d.split(/=/)}catch(h){continue}f[d[0]]?(f[d[0]].splice||(e=f[d[0]],f[d[0]]=[],f[d[0]].push(e)),f[d[0]].push(d[1])):f[d[0]]=d[1]}return C.debug(null,["Getting query params from string",a,f]),f}function f(b,c){return b[c]===a.mockjaxSettings[c]}function g(b,c){if(a.isFunction(b))return b(c);if(a.isFunction(b.url.test)){if(!b.url.test(c.url))return null}else{var e=b.namespace||a.mockjaxSettings.namespace;if(e){var f=[e,b.url].join("/");f=f.replace(/(\/+)/g,"/"),b.url=f}var g=b.url.indexOf("*");if(b.url!==c.url&&-1===g||!new RegExp(b.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g,"\\$&").replace(/\*/g,".+")).test(c.url))return null}if(b.requestHeaders){if(void 0===c.headers)return null;var h=!1;if(a.each(b.requestHeaders,function(a,b){var d=c.headers[a];return d!==b?(h=!0,!1):void 0}),h)return null}return!b.data||c.data&&d(b.data,c.data)?b&&b.type&&b.type.toLowerCase()!==c.type.toLowerCase()?null:b:null}function h(a){return"number"==typeof a&&a>=0}function i(b){if(a.isArray(b)&&2===b.length){var c=b[0],d=b[1];if(h(c)&&h(d))return Math.floor(Math.random()*(d-c))+c}else if(h(b))return b;return B}function j(b,d,e){C.debug(b,["Sending fake XHR request",b,d,e]);var g=function(f){return function(){return function(){this.status=b.status,this.statusText=b.statusText,this.readyState=1;var g=function(){this.readyState=4;var e;"json"===d.dataType&&"object"==typeof b.responseText?this.responseText=JSON.stringify(b.responseText):"xml"===d.dataType?"string"==typeof b.responseXML?(this.responseXML=c(b.responseXML),this.responseText=b.responseXML):this.responseXML=b.responseXML:"object"==typeof b.responseText&&null!==b.responseText?(b.contentType="application/json",this.responseText=JSON.stringify(b.responseText)):this.responseText=b.responseText,"number"!=typeof b.status&&"string"!=typeof b.status||(this.status=b.status),"string"==typeof b.statusText&&(this.statusText=b.statusText),e=this.onload||this.onreadystatechange,a.isFunction(e)?(b.isTimeout&&(this.status=-1),e.call(this,b.isTimeout?"timeout":void 0)):b.isTimeout&&(this.status=-1)};if(a.isFunction(b.response)){if(2===b.response.length)return void b.response(e,function(){g.call(f)});b.response(e)}g.call(f)}.apply(f)}}(this);b.proxy?(C.info(b,["Retrieving proxy file: "+b.proxy,b]),v({global:!1,url:b.proxy,type:b.proxyType,data:b.data,async:d.async,dataType:"script"===d.dataType?"text/plain":d.dataType,complete:function(a){b.responseXML=b.responseText=a.responseText,f(b,"status")&&(b.status=a.status),f(b,"statusText")&&(b.statusText=a.statusText),d.async===!1?g():this.responseTimer=setTimeout(g,i(b.responseTime))}})):d.async===!1?g():this.responseTimer=setTimeout(g,i(b.responseTime))}function k(b,c,d,e){return C.debug(b,["Creating new mock XHR object",b,c,d,e]),b=a.extend(!0,{},a.mockjaxSettings,b),"undefined"==typeof b.headers&&(b.headers={}),"undefined"==typeof c.headers&&(c.headers={}),b.contentType&&(b.headers["content-type"]=b.contentType),{status:b.status,statusText:b.statusText,readyState:1,open:function(){},send:function(){e.fired=!0,j.call(this,b,c,d)},abort:function(){clearTimeout(this.responseTimer)},setRequestHeader:function(a,b){c.headers[a]=b},getResponseHeader:function(a){return b.headers&&b.headers[a]?b.headers[a]:"last-modified"===a.toLowerCase()?b.lastModified||(new Date).toString():"etag"===a.toLowerCase()?b.etag||"":"content-type"===a.toLowerCase()?b.contentType||"text/plain":void 0},getAllResponseHeaders:function(){var c="";return b.contentType&&(b.headers["Content-Type"]=b.contentType),a.each(b.headers,function(a,b){c+=a+": "+b+"\n"}),c}}}function l(a,b,c){if(m(a),a.dataType="json",a.data&&z.test(a.data)||z.test(a.url)){p(a,b,c);var d=/^(\w+:)?\/\/([^\/?#]+)/,e=d.exec(a.url),f=e&&(e[1]&&e[1]!==location.protocol||e[2]!==location.host);if(a.dataType="script","GET"===a.type.toUpperCase()&&f){var g=n(a,b,c);return g?g:!0}}return null}function m(a){"GET"===a.type.toUpperCase()?z.test(a.url)||(a.url+=(/\?/.test(a.url)?"&":"?")+(a.jsonp||"callback")+"=?"):a.data&&z.test(a.data)||(a.data=(a.data?a.data+"&":"")+(a.jsonp||"callback")+"=?")}function n(b,c,d){C.debug(c,["Performing JSONP request",c,b,d]);var e=d&&d.context||b,f=a.Deferred?new a.Deferred:null;if(c.response&&a.isFunction(c.response))c.response(d);else if("object"==typeof c.responseText)a.globalEval("("+JSON.stringify(c.responseText)+")");else{if(c.proxy)return C.info(c,["Performing JSONP proxy request: "+c.proxy,c]),v({global:!1,url:c.proxy,type:c.proxyType,data:c.data,dataType:"script"===b.dataType?"text/plain":b.dataType,complete:function(d){a.globalEval("("+d.responseText+")"),o(b,c,e,f)}}),f;a.globalEval("("+("string"==typeof c.responseText?'"'+c.responseText+'"':c.responseText)+")")}return o(b,c,e,f),f}function o(b,c,d,e){var f;setTimeout(function(){if(q(b,d,c),r(b,d),e){try{f=a.parseJSON(c.responseText)}catch(g){}e.resolveWith(d,[f||c.responseText]),C.log(c,["JSONP mock call complete",c,e])}},i(c.responseTime))}function p(a,c,d){var e=d&&d.context||a,f="string"==typeof a.jsonpCallback&&a.jsonpCallback||"jsonp"+A++;a.data&&(a.data=(a.data+"").replace(z,"="+f+"$1")),a.url=a.url.replace(z,"="+f+"$1"),b[f]=b[f]||function(){q(a,e,c),r(a,e),b[f]=void 0;try{delete b[f]}catch(d){}},a.jsonpCallback=f}function q(b,c,d){b.success&&b.success.call(c,d.responseText||"","success",{}),b.global&&(b.context?a(b.context):a.event).trigger("ajaxSuccess",[{},b])}function r(b,c){b.complete&&b.complete.call(c,{statusText:"success",status:200},"success"),b.global&&(b.context?a(b.context):a.event).trigger("ajaxComplete",[{},b]),b.global&&!--a.active&&a.event.trigger("ajaxStop")}function s(b,c){var d,e,f,h;C.debug(null,["Ajax call intercepted",b,c]),"object"==typeof b?(c=b,b=void 0):(c=c||{},c.url=b||c.url),e=a.ajaxSetup({},c),e.type=e.method=e.method||e.type,h=function(b,d){var e=c[b.toLowerCase()];return function(){a.isFunction(e)&&e.apply(this,[].slice.call(arguments)),d["onAfter"+b]()}};for(var i=0;i<w.length;i++)if(w[i]){if(f=g(w[i],e))return a.mockjaxSettings.retainAjaxCalls&&x.push(e),C.info(f,["MOCK "+e.type.toUpperCase()+": "+e.url,a.ajaxSetup({},e)]),e.dataType&&"JSONP"===e.dataType.toUpperCase()&&(d=l(e,f,c))?d:(c.crossDomain=!1,f.cache=e.cache,f.timeout=e.timeout,f.global=e.global,f.isTimeout&&(f.responseTime>1?c.timeout=f.responseTime-1:(f.responseTime=2,c.timeout=1)),a.isFunction(f.onAfterSuccess)&&(c.success=h("Success",f)),a.isFunction(f.onAfterError)&&(c.error=h("Error",f)),a.isFunction(f.onAfterComplete)&&(c.complete=h("Complete",f)),t(f,c),function(b,c,e,f){d=v.call(a,a.extend(!0,{},e,{xhr:function(){return k(b,c,e,f)}}))}(f,e,c,w[i]),d);C.debug(w[i],["Mock does not match request",b,e])}if(C.log(null,["No mock matched to request",b,c]),a.mockjaxSettings.retainAjaxCalls&&y.push(c),a.mockjaxSettings.throwUnmocked===!0)throw new Error("AJAX not mocked: "+c.url);return v.apply(a,[c])}function t(a,b){if(a.url instanceof RegExp&&a.hasOwnProperty("urlParams")){var c=a.url.exec(b.url);if(1!==c.length){c.shift();var d=0,e=c.length,f=a.urlParams.length,g=Math.min(e,f),h={};for(d;g>d;d++){var i=a.urlParams[d];h[i]=c[d]}b.urlParams=h}}}function u(a){var b,c,d,e=[],f=a instanceof RegExp?function(b){return a.test(b)}:function(b){return a===b};for(b=0,c=w.length;c>b;b++)d=w[b],f(d.url)?C.log(d,["Clearing mock: "+(d&&d.url),d]):e.push(d);return e}var v=a.ajax,w=[],x=[],y=[],z=/=\?(&|$)/,A=(new Date).getTime(),B=500;a.extend({ajax:s});var C={_log:function(b,c,d){var e=a.mockjaxSettings.logging;return b&&"undefined"!=typeof b.logging&&(e=b.logging),d=0===d?d:d||D.LOG,c=c.splice?c:[c],e===!1||d>e?void 0:a.mockjaxSettings.log?a.mockjaxSettings.log(b,c[1]||c[0]):a.mockjaxSettings.logger&&a.mockjaxSettings.logger[a.mockjaxSettings.logLevelMethods[d]]?a.mockjaxSettings.logger[a.mockjaxSettings.logLevelMethods[d]].apply(a.mockjaxSettings.logger,c):void 0},debug:function(a,b){return C._log(a,b,D.DEBUG)},log:function(a,b){return C._log(a,b,D.LOG)},info:function(a,b){return C._log(a,b,D.INFO)},warn:function(a,b){return C._log(a,b,D.WARN)},error:function(a,b){return C._log(a,b,D.ERROR)}},D={DEBUG:4,LOG:3,INFO:2,WARN:1,ERROR:0};return a.mockjaxSettings={log:null,logger:b.console,logging:2,logLevelMethods:["error","warn","info","log","debug"],namespace:null,status:200,statusText:"OK",responseTime:B,isTimeout:!1,throwUnmocked:!1,retainAjaxCalls:!0,contentType:"text/plain",response:"",responseText:"",responseXML:"",proxy:"",proxyType:"GET",lastModified:null,etag:"",headers:{etag:"IJF@H#@923uf8023hFO@I#H#","content-type":"text/plain"}},a.mockjax=function(b){if(a.isArray(b))return a.map(b,function(b){return a.mockjax(b)});var c=w.length;return w[c]=b,C.log(b,["Created new mock handler",b]),c},a.mockjax._logger=C,a.mockjax.clear=function(a){"string"==typeof a||a instanceof RegExp?w=u(a):a||0===a?(C.log(w[a],["Clearing mock: "+(w[a]&&w[a].url),w[a]]),w[a]=null):(C.log(null,"Clearing all mocks"),w=[]),x=[],y=[]},a.mockjax.clearRetainedAjaxCalls=function(){x=[],y=[],C.debug(null,"Cleared retained ajax calls")},a.mockjax.handler=function(a){return 1===arguments.length?w[a]:void 0},a.mockjax.mockedAjaxCalls=function(){return x},a.mockjax.unfiredHandlers=function(){for(var a=[],b=0,c=w.length;c>b;b++){var d=w[b];null===d||d.fired||a.push(d)}return a},a.mockjax.unmockedAjaxCalls=function(){return y},a.mockjax});

@@ -22,3 +22,3 @@ module.exports = function(grunt) {

].join('\n'),
// Task configuration

@@ -69,6 +69,6 @@ concat: {

'1.11.3',
'1.12.0',
'1.12.4',
'2.0.3',
'2.1.4',
'2.2.0'
'2.2.4'
]

@@ -83,6 +83,6 @@ },

'1.11.3',
'1.12.0',
'1.12.4',
'2.0.3',
'2.1.4',
'2.2.0'
'2.2.4'
]

@@ -92,4 +92,4 @@ },

jQueryVersions: [
'1.12.0',
'2.2.0'
'1.12.4',
'2.2.4'
]

@@ -100,5 +100,5 @@ },

'1.5.2',
'1.12.0',
'1.12.4',
'2.1.4',
'2.2.0'
'2.2.4'
]

@@ -119,6 +119,6 @@ },

'1.11.3',
'1.12.0',
'1.12.4',
'2.0.3',
'2.1.4',
'2.2.0'
'2.2.4'
]

@@ -158,3 +158,3 @@ }

grunt.log.writeln('Adding jQuery version to test: ' + versions[i]);
if (arguments[0] === 'requirejs') {

@@ -171,2 +171,2 @@ versionUrls.push('./test/requirejs/' + file + '?jquery=' + versions[i]);

};
};
{
"name": "jquery-mockjax",
"title": "jQuery Mockjax",
"version": "2.1.1",
"version": "2.2.0",
"main": "./src/jquery.mockjax.js",

@@ -62,7 +62,8 @@ "description": "The jQuery Mockjax Plugin provides a simple and extremely flexible interface for mocking or simulating ajax requests and responses.",

"grunt-mocha-test": "^0.12.7",
"jsdom": "^4.2.0",
"jsdom": "~4.2.0",
"load-grunt-tasks": "^0.6.0",
"mocha": "^2.2.4",
"sinon": "^1.17.4",
"xmlhttprequest": "^1.7.0"
}
}

@@ -26,3 +26,4 @@ # jQuery Mockjax: Ajax request mocking #

* [Defining a Request to Match](#defining-a-request-to-match)
* [Define a Response](#define-a-response)
* [Defining Multiple Requests](#defining-multiple-requests)
* [Defining a Response](#defining-a-response)
* [Advanced Mocking Techniques](#advanced-mocking-techniques)

@@ -45,2 +46,3 @@ * [Simulating Response Time and Latency](#simulating-response-time-and-latency)

* [Browsers Tested](#browsers-tested)
* [Logging](#logging)
* [Release History](#release-history)

@@ -86,3 +88,3 @@ * [License](#license)

* `url`: [String | RegExp] Specifies the url of the request that the data should be mocked for. If it is a string and contains any asterisks ( `*` ), they will be treated as a wildcard by translating to a regular expression. Any `*` will be replaced with `.+`. If you run into trouble with this shortcut, switch to using a full regular expression instead of a string and asterisk combination
* `data`: [Object] In addition to the URL, match parameters
* `data`: [Object | Function] In addition to the URL, match parameters
* `type`: [String] Specify what HTTP method to match, usually GET or POST. Case-insensitive, so `get` and `post` also work

@@ -113,2 +115,3 @@ * `headers`: [Object] Keys will be simulated as additional headers returned from the server for the request (**NOTE: This is NOT used to match request headers!**)

* Returns an array of all mocked ajax calls with each entry being the request settings object as passed into the `$.mockjax()` function
* If `$.mockjaxSettings.retainAjaxCalls is set to false, this will always be empty
* `Array<Object> $.mockjax.unfiredHandlers()`

@@ -118,2 +121,5 @@ * Returns an array of all mock handler settings that have not been used. In other words, if a handler has been used for a `$.ajax()` call then it will _not_ appear in this array

* Returns an array of all unmocked Ajax calls that were made. The array contains the settings object passed into `$.ajax({...})`
* If `$.mockjaxSettings.retainAjaxCalls is set to false, this will always be empty
* `void $.mockjax.clearRetainedAjaxCalls()`
* Empties the arrays returned by `$.mockjax.mockedAjaxCalls` and `$.mockjax.unmockedAjaxCalls`

@@ -266,7 +272,32 @@ ### Overview: Your First Mock ###

$.mockjax({
url: "/rest",
data: { action: "foo" }
url: "/rest",
data: { action: "foo" }
});
```
The data option may be a custom matching function returning `true` of `false`
whether the data is expected or not:
```javascript
$.mockjax([
url: "/rest",
data: function( data ) {
return deepEqual( data, expected );
}
]);
```
The data function is a recommended place for assertions. Return `true` and let
a testing framework of choice do the rest:
```javascript
$.mockjax([
url: "/rest",
data: function ( json ) {
assert.deepEqual( JSON.parse(json), expected ); // QUnit example.
return true;
}
]);
```
To capture URL parameters, use a capturing regular expression for the

@@ -291,4 +322,19 @@ URL and a `urlParams` array to indicate, ordinally, the names of the

### Define a Response ###
### Defining Multiple Requests ###
Since version 2.2 it is allowed to define several requests at once.
`$.mockjax([...])` returns a array of handlers' indexes. It is possible to
reset handler by index. Read more in [Removing Mockjax Handlers](#removing-mockjax-handlers).
```javascript
var handlers = $.mockjax([
{url: '/rest', responseText: 'one'},
{url: '/rest', responseText: 'two'}
]);
$.mockjax.clear(handlers[0]);
```
### Defining a Response ###
The second step is to define the type and content of the response. The two main

@@ -355,5 +401,5 @@ properties you will be dealing with are either `responseText` or

> Note: If you're testing your code with a poxy, it is best to run an actual web
server for the tests. Simply loading `test/index.html` from the file system may
result in the proxy file not being loaded correctly. We recommend using something
> Note: If you're testing your code with a poxy, it is best to run an actual web
server for the tests. Simply loading `test/index.html` from the file system may
result in the proxy file not being loaded correctly. We recommend using something
like the [`http-server` npm module](https://www.npmjs.com/package/http-server).

@@ -617,17 +663,21 @@

{
logging: true,
namespace: null,
status: 200,
statusText: "OK",
responseTime: 500,
isTimeout: false,
throwUnmocked: false,
contentType: "text/plain",
response: "",
responseText: "",
responseXML: "",
proxy: "",
proxyType: "GET",
lastModified: null,
etag: "",
log: null, // DEPRECATED, use $.mockjaxSettings.logger instead
logger: window.console,
logging: 2,
logLevelMethods: ['error', 'warn', 'info', 'log', 'debug'],
namespace: null,
status: 200,
statusText: "OK",
responseTime: 500,
isTimeout: false,
throwUnmocked: false,
retainAjaxCalls: true,
contentType: "text/plain",
response: "",
responseText: "",
responseXML: "",
proxy: "",
proxyType: "GET",
lastModified: null,
etag: "",
headers: {

@@ -720,2 +770,60 @@ etag: "IJF@H#@923uf8023hFO@I#H#",

### Logging ###
Mockjax logs various pieces of information to the `console` (on `window`) in
browsers, or to stdout in Node). You can customize various aspects of the
logging to suit your needs. By default, only 'error', 'warn' or 'info' messages
will be shown, but detailed information may be available in debug logs. Below
are some common things you might need to do to get better logging information.
#### Show different levels of log messages
```js
$.mockjaxSettings.logging = 4; // very verbose debug messages
$.mockjaxSettings.logging = 3; // verbose log messages
$.mockjaxSettings.logging = 2; // informational messages
$.mockjaxSettings.logging = 1; // warning messages
$.mockjaxSettings.logging = 0; // only critical error messages
```
(Note that each level enables that level plus any lower number... thus setting
logging to `2` also enables warnings and errors.)
#### Implement a custom logger
If you don't want to use the `console` object, you can pass in your own logging
implementation with the `logger` setting. Note that your logger must either
implement the `debug`, `log`, `info`, `warn`, and `error` methods, or you must
also provide what methods map to the 5 levels (0 through 4).
```js
$.mockjaxSettings.logger = {
debug: function() { ... },
log: function() { ... },
// ...
};
```
Your logger methods may receive any number of arguments to log out, either as
strings or objects, similar to how the `window.console` object methods work.
If you have a logger that uses different methods names, specify them in this array:
```js
$.mockjaxSettings.logLevelMethods = ['critical', 'bad', 'stuff', 'log', 'verbose'];
```
Note that the first entry in this array (index `0`) will be errors while the last
entry will be verbose output. Anything beyond index `4` will be ignored.
#### What about the old `log` setting?
This was an undocumented feature whereby you could provide a `log` method using
`$.mockjaxSettings`, however, it is no longer used internally. This undocumented
option is now **deprecated**, and while it will work, log messages of ALL levels
will be sent to it.
If you have no idea what we're talking about... good! Don't worry about it. The
proper way to implement your own logger is via `$.mockjaxSettings.logger`.
### Release History ###

@@ -722,0 +830,0 @@

@@ -31,5 +31,5 @@ (function(root, factory) {

CALLBACK_REGEX = /=\?(&|$)/,
jsc = (new Date()).getTime();
jsc = (new Date()).getTime(),
DEFAULT_RESPONSE_TIME = 500;
// Parse the given XML string.

@@ -69,3 +69,9 @@ function parseXML(xml) {

function isMockDataEqual( mock, live ) {
logger.debug( mock, ['Checking mock data against request data', mock, live] );
var identical = true;
if ( $.isFunction(mock) ) {
return !!mock(live);
}
// Test for situations where the data is a querystring (not an object)

@@ -82,3 +88,3 @@ if (typeof live === 'string') {

}
$.each(mock, function(k) {

@@ -106,3 +112,3 @@ if ( live[k] === undefined ) {

}
function getQueryParams(queryString) {

@@ -112,3 +118,3 @@ var i, l, param, tmp,

params = String(queryString).split(/&/);
for (i=0, l=params.length; i<l; ++i) {

@@ -123,3 +129,3 @@ param = params[i];

}
if (paramsObj[param[0]]) {

@@ -138,3 +144,5 @@ // this is an array query param (more than one entry in query)

}
logger.debug( null, ['Getting query params from string', queryString, paramsObj] );
return paramsObj;

@@ -238,2 +246,3 @@ }

function _xhrSend(mockHandler, requestSettings, origSettings) {
logger.debug( mockHandler, ['Sending fake XHR request', mockHandler, requestSettings, origSettings] );

@@ -313,2 +322,3 @@ // This is a substitute for < 1.4 which lacks $.proxy

if ( mockHandler.proxy ) {
logger.info( mockHandler, ['Retrieving proxy file: ' + mockHandler.proxy, mockHandler] );
// We're proxying this request and loading in an external file instead

@@ -327,3 +337,3 @@ _ajax({

mockHandler.responseXML = mockHandler.responseText = xhr.responseText;
// Don't override the handler status/statusText if it's specified by the config

@@ -359,2 +369,4 @@ if (isDefaultSetting(mockHandler, 'status')) {

function xhr(mockHandler, requestSettings, origSettings, origHandler) {
logger.debug( mockHandler, ['Creating new mock XHR object', mockHandler, requestSettings, origSettings, origHandler] );
// Extend with our default mockjax settings

@@ -463,2 +475,4 @@ mockHandler = $.extend(true, {}, $.mockjaxSettings, mockHandler);

function processJsonpRequest( requestSettings, mockHandler, origSettings ) {
logger.debug( mockHandler, ['Performing JSONP request', mockHandler, requestSettings, origSettings] );
// Synthesize the mock request for adding a script tag

@@ -480,2 +494,3 @@ var callbackContext = origSettings && origSettings.context || requestSettings,

} else if (mockHandler.proxy) {
logger.info( mockHandler, ['Performing JSONP proxy request: ' + mockHandler.proxy, mockHandler] );

@@ -499,4 +514,4 @@ // This handles the unique case where we have a remote URL, but want to proxy the JSONP

} else {
$.globalEval( '(' +
((typeof mockHandler.responseText === 'string') ?
$.globalEval( '(' +
((typeof mockHandler.responseText === 'string') ?
('"' + mockHandler.responseText + '"') : mockHandler.responseText) +

@@ -518,11 +533,12 @@ ')');

jsonpComplete( requestSettings, callbackContext );
}, parseResponseTimeOpt( mockHandler.responseTime ));
if ( newMock ) {
try {
json = $.parseJSON( mockHandler.responseText );
} catch (err) { /* just checking... */ }
if ( newMock ) {
try {
json = $.parseJSON( mockHandler.responseText );
} catch (err) { /* just checking... */ }
newMock.resolveWith( callbackContext, [json || mockHandler.responseText] );
}
newMock.resolveWith( callbackContext, [json || mockHandler.responseText] );
logger.log( mockHandler, ['JSONP mock call complete', mockHandler, newMock] );
}
}, parseResponseTimeOpt( mockHandler.responseTime ));
}

@@ -596,2 +612,4 @@

logger.debug( null, ['Ajax call intercepted', url, origSettings] );
// If url is an object, simulate pre-1.5 signature

@@ -632,2 +650,3 @@ if ( typeof url === 'object' ) {

if(!mockHandler) {
logger.debug( mockHandlers[k], ['Mock does not match request', url, requestSettings] );
// No valid mock found for this request

@@ -637,6 +656,11 @@ continue;

mockedAjaxCalls.push(requestSettings);
if ($.mockjaxSettings.retainAjaxCalls) {
mockedAjaxCalls.push(requestSettings);
}
// If logging is enabled, log the mock to the console
$.mockjaxSettings.log( mockHandler, requestSettings );
logger.info( mockHandler, [
'MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url,
$.ajaxSetup({}, requestSettings)
] );

@@ -651,7 +675,7 @@

// We are mocking, so there will be no cross domain request, however, jQuery
// aggressively pursues this if the domains don't match, so we need to
// explicitly disallow it. (See #136)
origSettings.crossDomain = false;
// We are mocking, so there will be no cross domain request, however, jQuery
// aggressively pursues this if the domains don't match, so we need to
// explicitly disallow it. (See #136)
origSettings.crossDomain = false;
// Removed to fix #54 - keep the mocking data object intact

@@ -703,3 +727,6 @@ //mockHandler.data = requestSettings.data;

// We don't have a mock request
unmockedAjaxCalls.push(origSettings);
logger.log( null, ['No mock matched to request', url, origSettings] );
if ($.mockjaxSettings.retainAjaxCalls) {
unmockedAjaxCalls.push(origSettings);
}
if($.mockjaxSettings.throwUnmocked === true) {

@@ -763,2 +790,7 @@ throw new Error('AJAX not mocked: ' + origSettings.url);

results.push(handler);
} else {
logger.log( handler, [
'Clearing mock: ' + (handler && handler.url),
handler
] );
}

@@ -776,55 +808,127 @@ }

var DEFAULT_RESPONSE_TIME = 500;
var logger = {
_log: function logger( mockHandler, args, level ) {
var loggerLevel = $.mockjaxSettings.logging;
if (mockHandler && typeof mockHandler.logging !== 'undefined') {
loggerLevel = mockHandler.logging;
}
level = ( level === 0 ) ? level : ( level || logLevels.LOG );
args = (args.splice) ? args : [ args ];
$.mockjaxSettings = {
//url: null,
//type: 'GET',
log: function( mockHandler, requestSettings ) {
if ( mockHandler.logging === false ||
( typeof mockHandler.logging === 'undefined' && $.mockjaxSettings.logging === false ) ) {
// Is logging turned off for this mock or mockjax as a whole?
// Or is this log message above the desired log level?
if ( loggerLevel === false || loggerLevel < level ) {
return;
}
if ( window.console && console.log ) {
var message = 'MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url;
var request = $.ajaxSetup({}, requestSettings);
if (typeof console.log === 'function') {
console.log(message, request);
} else {
try {
console.log( message + ' ' + JSON.stringify(request) );
} catch (e) {
console.log(message);
}
}
if ( $.mockjaxSettings.log ) {
return $.mockjaxSettings.log( mockHandler, args[1] || args[0] );
} else if ( $.mockjaxSettings.logger && $.mockjaxSettings.logger[$.mockjaxSettings.logLevelMethods[level]] ) {
return $.mockjaxSettings.logger[$.mockjaxSettings.logLevelMethods[level]].apply( $.mockjaxSettings.logger, args );
}
},
logging: true,
namespace: null,
status: 200,
statusText: 'OK',
responseTime: DEFAULT_RESPONSE_TIME,
isTimeout: false,
throwUnmocked: false,
contentType: 'text/plain',
response: '',
responseText: '',
responseXML: '',
proxy: '',
proxyType: 'GET',
/**
* Convenience method for logging a DEBUG level message
* @param {Object} m The mock handler in question
* @param {Array|String|Object} a The items to log
* @return {?} Will return whatever the $.mockjaxSettings.logger method for this level would return (generally 'undefined')
*/
debug: function(m,a) { return logger._log(m,a,logLevels.DEBUG); },
/**
* @see logger.debug
*/
log: function(m,a) { return logger._log(m,a,logLevels.LOG); },
/**
* @see logger.debug
*/
info: function(m,a) { return logger._log(m,a,logLevels.INFO); },
/**
* @see logger.debug
*/
warn: function(m,a) { return logger._log(m,a,logLevels.WARN); },
/**
* @see logger.debug
*/
error: function(m,a) { return logger._log(m,a,logLevels.ERROR); }
};
lastModified: null,
etag: '',
headers: {
etag: 'IJF@H#@923uf8023hFO@I#H#',
'content-type' : 'text/plain'
}
var logLevels = {
DEBUG: 4,
LOG: 3,
INFO: 2,
WARN: 1,
ERROR: 0
};
/**
* Default settings for mockjax. Some of these are used for defaults of
* individual mock handlers, and some are for the library as a whole.
* For individual mock handler settings, please see the README on the repo:
* https://github.com/jakerella/jquery-mockjax#api-methods
*
* @type {Object}
*/
$.mockjaxSettings = {
log: null, // this is only here for historical purposes... use $.mockjaxSettings.logger
logger: window.console,
logging: 2,
logLevelMethods: ['error', 'warn', 'info', 'log', 'debug'],
namespace: null,
status: 200,
statusText: 'OK',
responseTime: DEFAULT_RESPONSE_TIME,
isTimeout: false,
throwUnmocked: false,
retainAjaxCalls: true,
contentType: 'text/plain',
response: '',
responseText: '',
responseXML: '',
proxy: '',
proxyType: 'GET',
lastModified: null,
etag: '',
headers: {
etag: 'IJF@H#@923uf8023hFO@I#H#',
'content-type' : 'text/plain'
}
};
/**
* Create a new mock Ajax handler. When a mock handler is matched during a
* $.ajax() call this library will intercept that request and fake a response
* using the data and methods in the mock. You can see all settings in the
* README of the main repository:
* https://github.com/jakerella/jquery-mockjax#api-methods
*
* @param {Object} settings The mock handelr settings: https://github.com/jakerella/jquery-mockjax#api-methods
* @return {Number} The id (index) of the mock handler suitable for clearing (see $.mockjax.clear())
*/
$.mockjax = function(settings) {
// Multiple mocks.
if ( $.isArray(settings) ) {
return $.map(settings, function(s) {
return $.mockjax(s);
});
}
var i = mockHandlers.length;
mockHandlers[i] = settings;
logger.log( settings, ['Created new mock handler', settings] );
return i;
};
$.mockjax._logger = logger;
/**
* Remove an Ajax mock from those held in memory. This will prevent any
* future Ajax request mocking for matched requests.
* NOTE: Clearing a mock will not prevent the resolution of in progress requests
*
* @param {Number|String|RegExp} i OPTIONAL The mock to clear. If not provided, all mocks are cleared,
* if a number it is the index in the in-memory cache. If a string or
* RegExp, find a mock that matches that URL and clear it.
* @return {void}
*/
$.mockjax.clear = function(i) {

@@ -834,4 +938,9 @@ if ( typeof i === 'string' || i instanceof RegExp) {

} else if ( i || i === 0 ) {
logger.log( mockHandlers[i], [
'Clearing mock: ' + (mockHandlers[i] && mockHandlers[i].url),
mockHandlers[i]
] );
mockHandlers[i] = null;
} else {
logger.log( null, 'Clearing all mocks' );
mockHandlers = [];

@@ -842,2 +951,22 @@ }

};
/**
* By default all Ajax requests performed after loading Mockjax are recorded
* so that we can see which requests were mocked and which were not. This
* method allows the developer to clear those retained requests.
*
* @return {void}
*/
$.mockjax.clearRetainedAjaxCalls = function() {
mockedAjaxCalls = [];
unmockedAjaxCalls = [];
logger.debug( null, 'Cleared retained ajax calls' );
};
/**
* Retrive the mock handler with the given id (index).
*
* @param {Number} i The id (index) to retrieve
* @return {Object} The mock handler settings
*/
$.mockjax.handler = function(i) {

@@ -848,5 +977,18 @@ if ( arguments.length === 1 ) {

};
/**
* Retrieve all Ajax calls that have been mocked by this library during the
* current session (in other words, only since you last loaded this file).
*
* @return {Array} The mocked Ajax calls (request settings)
*/
$.mockjax.mockedAjaxCalls = function() {
return mockedAjaxCalls;
};
/**
* Return all mock handlers that have NOT been matched against Ajax requests
*
* @return {Array} The mock handlers
*/
$.mockjax.unfiredHandlers = function() {

@@ -862,2 +1004,9 @@ var results = [];

};
/**
* Retrieve all Ajax calls that have NOT been mocked by this library during
* the current session (in other words, only since you last loaded this file).
*
* @return {Array} The mocked Ajax calls (request settings)
*/
$.mockjax.unmockedAjaxCalls = function() {

@@ -864,0 +1013,0 @@ return unmockedAjaxCalls;

@@ -248,2 +248,3 @@ (function(qunit, $) {

assert.equal(xhr.statusText, 'success', 'Response was successful');
window.abcdef123456 = null;
done();

@@ -250,0 +251,0 @@ }

@@ -89,3 +89,4 @@ (function(qunit, $) {

var delay = ((new Date()) - ts);
assert.ok( delay >= 150, 'Correct delay simulation (' + delay + ')' );
// check against 140ms to allow for browser variance
assert.ok( delay >= 140, 'Correct delay simulation (' + delay + ')' );
assert.strictEqual( executed, 1, 'Callback execution order correct');

@@ -106,2 +107,4 @@ done();

window.abcdef123456 = function() {};
$.ajax({

@@ -112,4 +115,6 @@ url: 'http://foobar.com/jsonp-delay?callback=?',

var delay = ((new Date()) - ts);
assert.ok( delay >= 150, 'Correct delay simulation (' + delay + ')' );
// check against 140ms to allow for browser variance
assert.ok( delay >= 140, 'Correct delay simulation (' + delay + ')' );
assert.ok( executed, 'Callback execution order correct');
window.abcdef123456 = null;
done();

@@ -125,2 +130,26 @@ }

t('Response time with jsonp deferred response', function(assert) {
var done = assert.async();
var executed = false, ts = new Date();
window.abcdef123456 = function() {};
$.ajax({
url: 'http://foobar.com/jsonp-delay?callback=?',
dataType: 'jsonp'
}).done(function() {
var delay = ((new Date()) - ts);
// check against 140ms to allow for browser variance
assert.ok( delay >= 140, 'Correct delay simulation (' + delay + ')' );
assert.ok( executed, 'Callback execution order correct');
window.abcdef123456 = null;
done();
});
setTimeout(function() {
assert.ok( executed === false, 'No premature callback execution');
executed = true;
}, 30);
});
t('Response time with min and max values', function (assert) {

@@ -170,2 +199,2 @@ var done = assert.async();

})(window.QUnit, window.jQuery);
})(window.QUnit, window.jQuery);
(function(qunit, $) {
'use strict';
var t = qunit.test;
/* ----------------- */
qunit.module( 'Core' );
/* ----------------- */
t('Return XMLHttpRequest object from $.ajax', function(assert) {

@@ -62,3 +62,3 @@ $.mockjax({

});
t('Intercept proxy calls for XML', function(assert) {

@@ -69,3 +69,3 @@ $.mockjax({

});
$.ajax({

@@ -78,3 +78,3 @@ url: '/proxy',

assert.strictEqual($(doc).find('foo').length, 1, 'Foo element exists in XML');
assert.strictEqual($(doc).find('foo')[0].textContent, 'bar', 'XML content is correct');
assert.strictEqual($(doc).find('foo').text(), 'bar', 'XML content is correct');
},

@@ -87,3 +87,3 @@ error: qunit.noErrorCallbackExpected

var done = assert.async();
$.mockjax({

@@ -107,3 +107,3 @@ url: '/proxy',

var done = assert.async();
$.mockjax({

@@ -128,3 +128,3 @@ url: '/proxy',

var done = assert.async();
$.mockjax({

@@ -146,3 +146,3 @@ url: '/resource',

var done = assert.async();
$.mockjax({

@@ -171,3 +171,3 @@ url: '/response-callback',

var done = assert.async();
$.mockjax({

@@ -203,3 +203,3 @@ url: '/response-callback',

var done = assert.async();
$.mockjax({

@@ -227,3 +227,3 @@ url: '/response'

var done = assert.async();
$.mockjax({

@@ -262,3 +262,3 @@ url: '/response-callback',

var done = assert.async();
$.mockjax({

@@ -290,81 +290,5 @@ url: '/response-callback'

t('Get mocked ajax calls - GET', function(assert) {
t('Throw new error when throwUnmocked is set to true and unmocked ajax calls are fired', function(assert) {
var done = assert.async();
$.mockjax({
url: '/api/example/*'
});
$.ajax({
async: false,
type: 'GET',
url: '/api/example/1',
complete: function() {
var actualCalls = $.mockjax.mockedAjaxCalls();
assert.equal(actualCalls.length, 1, 'mockjax call made');
assert.equal(actualCalls[0].type, 'GET', 'mockjax call has expected method');
assert.equal(actualCalls[0].url, '/api/example/1', 'mockjax call has expected url');
done();
}
});
});
t('Test unmockedAjaxCalls returns the correct object when ajax call is not mocked and throwUnmocked is false', function(assert) {
var done = assert.async();
$.mockjaxSettings.throwUnmocked = false;
$.ajax({
async: true,
type: 'GET',
url: '/api/example/1',
complete: function() {
var unmockedAjaxCalls = $.mockjax.unmockedAjaxCalls();
assert.equal(unmockedAjaxCalls.length, 1, 'Wrong number of unmocked ajax calls were returned');
assert.equal(unmockedAjaxCalls[0].url, '/api/example/1', 'unmockedAjaxcall has unexpected url');
done();
}
});
});
t('Test unmockedAjaxCalls are cleared when mockjax.clear is called', function(assert) {
var done = assert.async();
$.mockjaxSettings.throwUnmocked = false;
$.ajax({
async: true,
type: 'GET',
url: '/api/example/1',
complete: function() {
assert.equal($.mockjax.unmockedAjaxCalls().length, 1, 'Wrong number of unmocked ajax calls were returned');
$.mockjax.clear();
assert.equal($.mockjax.unmockedAjaxCalls().length, 0, 'Unmocked ajax calls not removed by mockjax.clear');
done();
}
});
});
t('Test unmockedAjaxCalls returns nothing when no unmocked ajax calls occur', function(assert) {
var done = assert.async();
$.mockjax({
url: '/api/example/1'
});
$.ajax({
async: true,
type: 'GET',
url: '/api/example/1',
complete: function() {
var unmockedAjaxCalls = $.mockjax.unmockedAjaxCalls();
assert.equal(unmockedAjaxCalls.length, 0, 'No unmocked Ajax calls should have been returned');
done();
}
});
});
t('Throw new error when throwUnmocked is set to true and unmocked ajax calls are fired', function(assert) {
var done = assert.async();
$.mockjaxSettings.throwUnmocked = true;

@@ -391,3 +315,3 @@

var done = assert.async();
$.mockjax({

@@ -415,3 +339,3 @@ url: '/api/example/1'

var done = assert.async();
$.mockjax({

@@ -443,3 +367,3 @@ url: '/api/example/1'

var done = assert.async();
$.mockjax({

@@ -464,99 +388,6 @@ url: '/put-request',

t('Get mocked ajax calls - POST with data', function(assert) {
t('Preserve context when set in jsonp ajax requet', function(assert) {
var done = assert.async();
$.mockjax({
url: '/api/example/*'
});
$.ajax({
async: false,
type: 'POST',
url: '/api/example/2',
data: {a: 1},
complete: function() {
var actualCalls = $.mockjax.mockedAjaxCalls();
assert.equal(actualCalls.length, 1, 'mockjax call made');
assert.equal(actualCalls[0].type, 'POST', 'mockjax call has expected method');
assert.equal(actualCalls[0].url, '/api/example/2', 'mockjax call has expected url');
assert.deepEqual(actualCalls[0].data, {a: 1}, 'mockjax call has expected data');
done();
}
});
});
t('Get mocked ajax calls - JSONP', function(assert) {
var done = assert.async();
$.mockjax({
url: '/api/example/*',
contentType: 'text/json',
proxy: 'test_jsonp.js'
});
var callbackExecuted = false;
window.abcdef123456 = function() {
assert.ok(true, 'JSONP Callback executed');
callbackExecuted = true;
};
$.ajax({
url: '/api/example/jsonp?callback=?',
jsonpCallback: 'abcdef123456',
dataType: 'jsonp',
error: qunit.noErrorCallbackExpected,
complete: function() {
var actualCalls = $.mockjax.mockedAjaxCalls();
assert.equal(actualCalls.length, 1, 'Mockjax call made');
assert.equal(actualCalls[0].url, '/api/example/jsonp?callback=abcdef123456', 'mockjax call has expected jsonp url');
assert.ok(callbackExecuted, 'The jsonp callback was executed');
done();
}
});
});
t('multiple mockjax calls are made', function(assert) {
$.mockjax({
url: '/api/example/*'
});
assert.equal($.mockjax.mockedAjaxCalls().length, 0, 'Initially there are no saved ajax calls');
$.ajax({
async: false,
type: 'GET',
url: '/api/example/1'
});
$.ajax({
async: false,
type: 'GET',
url: '/api/example/2'
});
$.ajax({
async: false,
url: '/api/example/jsonp?callback=?',
jsonpCallback: 'foo123',
dataType: 'jsonp'
});
assert.equal($.mockjax.mockedAjaxCalls().length, 3, 'Afterwords there should be three saved ajax calls');
var mockedUrls = $.map($.mockjax.mockedAjaxCalls(), function(ajaxOptions) {
return ajaxOptions.url;
});
assert.deepEqual(mockedUrls, [
'/api/example/1',
'/api/example/2',
'/api/example/jsonp?callback=foo123'
], 'Mocked ajax calls are saved in execution order');
$.mockjax.clear();
assert.equal($.mockjax.mockedAjaxCalls().length, 0, 'After clearing there are no saved ajax calls');
});
t('Preserve context when set in jsonp ajax requet', function(assert) {
var done = assert.async();
$.mockjax({
url: '/jsonp*',

@@ -578,2 +409,3 @@ contentType: 'text/json',

assert.deepEqual(this, cxt, 'this is equal to context object');
window.abcdef123456 = null;
done();

@@ -585,3 +417,3 @@ });

var done = assert.async();
$.mockjax({

@@ -603,9 +435,10 @@ url: '/jsonp*',

assert.ok(this.jsonp, '\'this\' is the $.ajax object for this request.');
window.abcdef123456 = null;
done();
});
});
t('Dynamic mock definition', function(assert) {
var done = assert.async();
$.mockjax( function( settings ) {

@@ -633,3 +466,3 @@ var service = settings.url.match(/\/users\/(.*)$/);

var done = assert.async();
$.mockjax({

@@ -651,4 +484,113 @@ url: '/response-callback',

});
});
});
})(window.QUnit, window.jQuery);
t('Case-insensitive matching for request types', function(assert) {
var done = assert.async();
$.mockjax({
url: '/case_insensitive_match',
type: 'GET',
responseText: 'uppercase type response'
});
$.ajax({
url: '/case_insensitive_match',
type: 'get',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.responseText, 'uppercase type response', 'Request matched regardless of case');
done();
}
});
});
t('Inspecting $.mockjax.handler(id) after request has fired', function(assert) {
var ID = $.mockjax({
url: '/mockjax_properties',
responseText: 'Hello Word'
});
$.ajax({
url: '/mockjax_properties',
complete: function() {}
});
assert.ok($.mockjax.handler(ID).fired, 'Sets the mock\'s fired property to true');
});
t('Inspecting $.mockjax() with multiple mocks argument', function(assert) {
var done = assert.async();
var handlers = $.mockjax([
{ url: '/response-callback', responseText: 'First' },
{ url: '/response-callback', responseText: 'Second' }
]);
assert.equal(handlers.length, 2, 'Not enough mocks')
var callCount = 2;
$.ajax({
url: '/response-callback',
complete: function() {
callCount--;
if (callCount === 0) {
done();
}
}
});
$.ajax({
url: '/response-callback',
complete: function() {
callCount--;
if (callCount === 0) {
done();
}
}
});
});
t('Inspecting $.mockjax() with empty multiple mocks argument', function(assert) {
var done = assert.async();
var handlers = $.mockjax([]);
assert.equal(handlers.length, 0)
$.ajax({
url: '/response-callback',
error: function() {
done();
}
});
});
t('Inspecting $.mockjax() with null in multiple mocks argument', function(assert) {
var done = assert.async();
var handlers = $.mockjax([ null ]);
assert.equal(handlers.length, 1)
$.ajax({
url: '/response-callback',
error: function() {
done();
}
});
});
t('Inspecting $.mockjax() with multiple mocks argument and reset handler', function(assert) {
var done = assert.async();
var handlers = $.mockjax([
{ url: '/rest', responseText: 'will be reset' }
]);
assert.equal(handlers.length, 1);
$.mockjax.clear(handlers[0]);
$.ajax({
url: '/response-callback',
error: function() {
done();
}
});
});
})(window.QUnit, window.jQuery);

@@ -255,2 +255,57 @@ (function(qunit, $) {

t('Multiple data matching requests with data function', function(assert) {
var done = assert.async();
$.mockjax({
url: '/response-callback',
data: function(data) {
return (data.answer === 'yes');
},
responseText: {'yes?': 'yes'}
});
$.mockjax({
url: '/response-callback',
data: function(data) {
return (data.answer === 'yes');
},
responseText: {'yes?': 'yes'}
});
var callCount = 2;
$.ajax({
url: '/response-callback',
data: {
answer: 'yes'
},
success: function(resp) {
assert.deepEqual( resp, {'yes?': 'yes'}, 'correct mock hander' );
},
complete: function() {
callCount--;
if (callCount <= 0) {
done();
}
}
});
var notMatched = false;
$.ajax({
url: '/response-callback',
data: {
answer: 'no'
},
error: function() {
notMatched = true;
},
complete: function() {
callCount--;
assert.ok( notMatched , 'correct data function' );
if (callCount <= 0) {
done();
}
}
});
});
t('Bug #106: Null matching on request', function(assert) {

@@ -257,0 +312,0 @@ var done = assert.async();

@@ -94,2 +94,3 @@ (function(qunit, $) {

assert.equal(xhr.getResponseHeader('Content-Type'), 'text/json', 'Content type of text/json');
window.abcdef123456 = null;
done();

@@ -180,5 +181,4 @@ }

assert.ok(true, 'Successfully grouped deferred responses');
done();
});
done();
});

@@ -209,2 +209,2 @@

})(window.QUnit, window.jQuery);
})(window.QUnit, window.jQuery);

@@ -1,26 +0,46 @@

(function(qunit, $) {
(function(qunit, $, sinon) {
'use strict';
var t = qunit.test;
var winLogger;
// Note: currently sinon cannot stub object methods in this manner in IE
// See GH issue: https://github.com/sinonjs/sinon/issues/1009
// As such, we'll be skipping the logger tests for IE currently
if (/MSIE/.test(navigator.userAgent)) {
qunit.module('Logging');
t('UNABLE TO TEST LOGGER IN IE', function(assert) {
assert.ok(true, 'Cannot stub console functions with Sinon, see https://github.com/sinonjs/sinon/issues/1009');
});
return;
}
/* -------------------- */
qunit.module( 'Logging' );
qunit.module( 'Logging', {
/* -------------------- */
t('Default log handler', function(assert) {
var done = assert.async();
if ( !window ) {
// We aren't running in a context with window available
done();
return;
beforeEach: function() {
winLogger = {
debug: sinon.stub(console, 'debug'),
log: sinon.stub(console, 'log'),
info: sinon.stub(console, 'info'),
warn: sinon.stub(console, 'warn'),
error: sinon.stub(console, 'error')
};
$.mockjaxSettings.logger = winLogger;
$.mockjaxSettings.logging = 2;
},
afterEach: function() {
winLogger.debug.restore();
winLogger.log.restore();
winLogger.info.restore();
winLogger.warn.restore();
winLogger.error.restore();
}
});
var _oldConsole = window.console;
var msg = null;
window.console = { log: function ( message ) {
msg = message;
}};
var _oldLogging = $.mockjaxSettings.logging;
$.mockjaxSettings.logging = true;
t('Default log handler (window.console)', function(assert) {
var done = assert.async();
$.mockjax({

@@ -33,5 +53,3 @@ url: '*'

complete: function() {
window.console = _oldConsole;
assert.equal(msg, 'MOCK GET: /console', 'Default log handler was not called');
$.mockjaxSettings.logging = _oldLogging;
assert.ok(winLogger.info.calledWith('MOCK GET: /console'), 'Default log handler was not called');
done();

@@ -42,9 +60,29 @@ }

t('Custom log handler', function(assert) {
t('Logging with high level', function(assert) {
$.mockjaxSettings.logging = 4;
$.mockjax._logger.debug({}, 'foobar');
$.mockjax._logger.info({}, 'foobar');
$.mockjax._logger.error({}, 'foobar');
assert.ok(winLogger.debug.calledWith('foobar'), 'Log handler 4 was not called for debug');
assert.ok(winLogger.info.calledWith('foobar'), 'Log handler 4 was not called for info');
assert.ok(winLogger.error.calledWith('foobar'), 'Log handler 4 was not called for error');
});
t('Logging with low level', function(assert) {
$.mockjaxSettings.logging = 0;
$.mockjax._logger.debug({}, 'foobar');
$.mockjax._logger.debug({ logging: 4 }, 'foobar');
$.mockjax._logger.info({}, 'foobar');
$.mockjax._logger.error({}, 'foobar');
assert.strictEqual(winLogger.debug.callCount, 1, 'Log handler 0 was called too much for debug');
assert.strictEqual(winLogger.info.callCount, 0, 'Log handler 0 was called for info');
assert.ok(winLogger.error.calledWith('foobar'), 'Log handler 4 was not called for error');
});
t('Custom (deprecated) log handler', function(assert) {
var done = assert.async();
var msg = null;
var _oldLog = $.mockjaxSettings.log;
$.mockjaxSettings.log = function( mockHandler, requestSettings) {
msg = requestSettings.type.toUpperCase() + ': ' + requestSettings.url;
$.mockjaxSettings.log = function customLogger( mockHandler, requestSettings) {
msg = mockHandler.url + ' - ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url;
};

@@ -58,4 +96,3 @@ $.mockjax({

complete: function() {
assert.equal(msg, 'GET: /console', 'Custom log handler was not called');
$.mockjaxSettings.log = _oldLog;
assert.equal(msg, '* - GET: /console', 'Custom log handler was not called');
done();

@@ -68,18 +105,3 @@ }

var done = assert.async();
if ( !window ) {
// We aren't running in a context with window available
done();
return;
}
var _oldConsole = window.console;
var msg = null;
window.console = { log: function ( message ) {
msg = message;
}};
var _oldLogging = $.mockjaxSettings.logging;
// Even though this is the suite default, we force it to be off
$.mockjaxSettings.logging = false;

@@ -93,5 +115,7 @@

complete: function() {
window.console = _oldConsole;
assert.equal(msg, null, 'Logging method incorrectly called');
$.mockjaxSettings.logging = _oldLogging;
assert.strictEqual(winLogger.info.callCount, 0, 'Log called when disabled');
$.mockjax._logger.debug({}, 'foo');
assert.strictEqual(winLogger.debug.callCount, 0, 'Log called when disabled');
done();

@@ -104,20 +128,3 @@ }

var done = assert.async();
if ( !window ) {
// We aren't running in a context with window available
done();
return;
}
var _oldConsole = window.console;
var msg = null;
window.console = { log: function ( message ) {
msg = message;
}};
var _oldLogging = $.mockjaxSettings.logging;
// Even though this is the suite default, we force it to be on
$.mockjaxSettings.logging = true;
$.mockjax({

@@ -131,39 +138,7 @@ url: '*',

complete: function() {
window.console = _oldConsole;
assert.equal(msg, null, 'Logging method incorrectly called');
$.mockjaxSettings.logging = _oldLogging;
done();
}
});
});
assert.strictEqual(winLogger.info.callCount, 0, 'Log called when disabled');
t('Inspecting $.mockjax.handler(id) after request has fired', function(assert) {
var ID = $.mockjax({
url: '/mockjax_properties',
responseText: 'Hello Word'
});
$.mockjax._logger.warn({}, 'foo');
assert.strictEqual(winLogger.warn.callCount, 1, 'General log not called when disabled per mock');
$.ajax({
url: '/mockjax_properties',
complete: function() {}
});
assert.ok($.mockjax.handler(ID).fired, 'Sets the mock\'s fired property to true');
});
t('Case-insensitive matching for request types', function(assert) {
var done = assert.async();
$.mockjax({
url: '/case_insensitive_match',
type: 'GET',
responseText: 'uppercase type response'
});
$.ajax({
url: '/case_insensitive_match',
type: 'get',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.responseText, 'uppercase type response', 'Request matched regardless of case');
done();

@@ -174,2 +149,3 @@ }

})(window.QUnit, window.jQuery);
})(window.QUnit, window.jQuery, window.sinon);
(function(qunit, $) {
'use strict';
qunit.begin(function() {
qunit.noErrorCallbackExpected = function noErrorCallbackExpected(xhr) {

@@ -13,6 +13,16 @@ qunit.assert.ok(false, 'Error callback executed: ' + xhr.status, xhr.responseText);

$.mockjaxSettings.logging = false;
// Don't show log messages, but allow logging to work
var noop = function() {};
$.mockjaxSettings.logger = {
debug: noop,
log: noop,
info: noop,
warn: noop,
error: noop
};
qunit.defaultMockjaxSettings = $.extend({}, $.mockjaxSettings);
});
qunit.testDone(function() {

@@ -23,2 +33,2 @@ $.mockjax.clear();

})(window.QUnit, window.jQuery);
})(window.QUnit, window.jQuery);

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc