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.5.1 to 2.6.0

lib/jquery-3.5.1.js

2

browserstack-config.js

@@ -17,6 +17,4 @@

"edge_latest",
"ie_9",
"ie_10",
"ie_11"
]
};
var browserstackRunner = require('browserstack-runner'),
config = require('./browserstack-config');
const browserstackRunner = require('browserstack-runner');
const config = require('./browserstack-config');

@@ -11,3 +11,3 @@ console.log(config);

}
console.log('All Done!');
console.log(JSON.stringify(report, null, 2));
});

@@ -0,1 +1,7 @@

## 2020-08-22 v2.6.0
* Removed support for IE 9 & 10
* Removed unused config for code climate
* Updated dev dependencies to fix browserstack and local test run issues
* Added support for regex url matching when using a namespace (thanks @gregid)
## 2020-03-30 v2.5.1

@@ -2,0 +8,0 @@ * Fixed issue with capitalization of the "content-type" header

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

@@ -168,5 +168,14 @@ * Copyright (c) 2020 Jordan Kasper, formerly appendTo;

// Apply namespace prefix to the mock handler's url.
var namespace = handler.namespace || (typeof(handler.namespace) === 'undefined' && $.mockjaxSettings.namespace);
// Inspect the URL of the request and check if the mock handler's url
// matches the url for this ajax request
if ( $.isFunction(handler.url.test) ) {
// namespace exists prepend handler.url with namespace
if (!!namespace) {
namespace = namespace.replace(/(\/+)$/, '');
var pattern = handler.url.source.replace(/^(\^+)/, '').replace(/^/, '^(' + namespace + ')?\/?');
handler.url = new RegExp(pattern);
}
// The user provided a regex for the url, test it

@@ -178,7 +187,4 @@ if ( !handler.url.test( requestSettings.url ) ) {

var effecitveUrl = handler.url;
var effectiveUrl = handler.url;
// Apply namespace prefix to the mock handler's url.
var namespace = handler.namespace || (typeof(handler.namespace) === 'undefined' && $.mockjaxSettings.namespace);
if (!!namespace) {

@@ -189,9 +195,9 @@ var namespacedUrl = [

].join('/');
effecitveUrl = namespacedUrl;
effectiveUrl = namespacedUrl;
}
// Look for a simple wildcard '*' or a direct URL match
var star = effecitveUrl.indexOf('*');
if (effecitveUrl !== requestSettings.url && star === -1 ||
!new RegExp(effecitveUrl.replace(/[-[\]{}()+?.,\\^$|#\s]/g, '\\$&').replace(/\*/g, '.+')).test(requestSettings.url)) {
var star = effectiveUrl.indexOf('*');
if (effectiveUrl !== requestSettings.url && star === -1 ||
!new RegExp(effectiveUrl.replace(/[-[\]{}()+?.,\\^$|#\s]/g, '\\$&').replace(/\*/g, '.+')).test(requestSettings.url)) {
return null;

@@ -198,0 +204,0 @@ }

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

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

@@ -82,3 +82,4 @@ var PORT = 4000;

'3.3.1',
'3.4.1'
'3.4.1',
'3.5.1'
]

@@ -93,3 +94,3 @@ },

'2.2.4',
'3.4.1'
'3.5.1'
]

@@ -101,3 +102,3 @@ },

'2.2.4',
'3.4.1'
'3.5.1'
]

@@ -110,3 +111,3 @@ },

'2.2.4',
'3.4.1'
'3.5.1'
]

@@ -135,3 +136,4 @@ },

'3.3.1',
'3.4.1'
'3.4.1',
'3.5.1'
]

@@ -138,0 +140,0 @@ },

{
"name": "jquery-mockjax",
"title": "jQuery Mockjax",
"version": "2.5.1",
"version": "2.6.0",
"main": "./src/jquery.mockjax.js",

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

"devDependencies": {
"browserify": "^13.1.0",
"browserstack-runner": "^0.7.0",
"grunt": "^1.0.1",
"grunt-browserify": "^5.0.0",
"browserify": "^16.5.2",
"browserstack-runner": "^0.9.3",
"grunt": "^1.3.0",
"grunt-browserify": "^5.3.0",
"grunt-contrib-concat": "^1.0.1",
"grunt-contrib-connect": "^1.0.2",
"grunt-contrib-jshint": "^1.1.0",
"grunt-contrib-qunit": "^1.2.0",
"grunt-contrib-uglify": "^2.0.0",
"grunt-contrib-watch": "^1.0.0",
"grunt-mocha-test": "^0.12.7",
"http-server": "^0.11.1",
"jsdom": "~4.2.0",
"load-grunt-tasks": "^0.6.0",
"mocha": "^2.2.4",
"puppeteer": "^1.1.1",
"sinon": "^1.17.4",
"xmlhttprequest": "^1.7.0"
"grunt-contrib-connect": "^3.0.0",
"grunt-contrib-jshint": "^2.1.0",
"grunt-contrib-qunit": "^4.0.0",
"grunt-contrib-uglify": "^5.0.0",
"grunt-contrib-watch": "^1.1.0",
"grunt-mocha-test": "^0.13.3",
"http-server": "^0.12.3",
"jsdom": "^16.4.0",
"load-grunt-tasks": "^5.1.0",
"mocha": "^8.1.1",
"puppeteer": "^5.2.1",
"sinon": "^9.0.3",
"xmlhttprequest": "^1.8.0"
}
}

@@ -40,3 +40,3 @@

try {
proc = spawn('http-server', ['-c-1', '-p ' + port]); // disable caching
proc = spawn('http-server', ['-c-1', '-p ' + port], { shell: true }); // disable caching

@@ -43,0 +43,0 @@ const browser = await puppeteer.launch();

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

[![Travis CI Badge](https://travis-ci.com/jakerella/jquery-mockjax.svg?branch=master)](https://travis-ci.com/jakerella/jquery-mockjax)
[![BrowserStack Status](https://automate.browserstack.com/badge.svg?badge_key=alZyelpKSWI1WlpxellOQXdPUHBMd2UvQnFmTTFnOEJ2V1FSVXo3a3JPbz0tLWk4alJ6aXJWZVV6bmN6QUZBUTQ5UVE9PQ==--fd0f170c41cb4b3eac0a35aaef09b1ead3b55a0cjquery-mockjax)](https://automate.browserstack.com/public-build/alZyelpKSWI1WlpxellOQXdPUHBMd2UvQnFmTTFnOEJ2V1FSVXo3a3JPbz0tLWk4alJ6aXJWZVV6bmN6QUZBUTQ5UVE9PQ==--fd0f170c41cb4b3eac0a35aaef09b1ead3b55a0cjquery-mockjax)
[![BrowserStack Status](https://automate.browserstack.com/badge.svg?badge_key=VTdsNjQzSDZvSXA2ZDhsamFkaG5pWWVFTmUwWDdmRmltTkFoY2VVR01COD0tLWVrSXY0YTJwWXNiZ2tlbmxBNTBpUmc9PQ==--e3dabee1a4e801501ff510bef8292859e10cb008)](https://automate.browserstack.com/public-build/VTdsNjQzSDZvSXA2ZDhsamFkaG5pWWVFTmUwWDdmRmltTkFoY2VVR01COD0tLWVrSXY0YTJwWXNiZ2tlbmxBNTBpUmc9PQ==--e3dabee1a4e801501ff510bef8292859e10cb008)

@@ -108,5 +108,6 @@ There are some minor breaking changes in v2, so if you need an older version, please check the [v1.x](https://github.com/jakerella/jquery-mockjax/tree/v1.x) branch or the list of [releases](https://github.com/jakerella/jquery-mockjax/tags) in Github.

* Returns the array of mock handlers. **NOTE:** This array is NOT modified when a handler is cleared, the cleared handler position is simply set to `null`. As such, the array length will only change when new mocks are added. Be careful here, you're accessing the inner workings of the plugin, any changes to the array could be very bad.
* `void $.mockjax.clear([/* Number */ id])`
* If the `id` is provided, the handler with that ID is cleared (that is, requests matching it will no longer do so, the handler is completely removed)
* If no `id` is provided, all handlers are cleared, resetting Mockjax to its initial state
* `void $.mockjax.clear([/* Number || String */ identifier])`
* If the `identifier` provided is a Number, the handler with that ID is cleared (that is, requests matching it will no longer do so, the handler is completely removed)
* If the `identifier` provided is a String, the handler with that matching URL is cleared.
* If no `identifier` is provided, *ALL handlers are cleared*, resetting Mockjax to its initial state
* `Array<Object> $.mockjax.mockedAjaxCalls()`

@@ -724,2 +725,9 @@ * Returns an array of all mocked ajax calls with each entry being the request settings object as passed into the `$.mockjax()` function

As will the following RegExp pattern:
```javascript
$.mockjax({
url: /^\/rest$/
})
```
The global namespace option can also be overwritten on a particular mock.

@@ -784,3 +792,16 @@

Or you can clear a handler by the URL that it matches with either a String or RegExp:
```javascript
$.mockjax({
url: "/api/foo",
...
});
$.mockjax.clear("/api/foo");
// or
$.mockjax.clear(/foo/);
```
## Miscellaneous Information ##

@@ -807,3 +828,3 @@

* Safari
* Internet Explorer 9-11
* Internet Explorer 11 (although it may work on IE 9 & 10)

@@ -933,8 +954,1 @@ Each PR will run these tests using TravisCI for continuous integration before

Pull Request ready for merging.
#### Admins ####
All pull requests are reviewed by the wonderful collaborators on this project:
* [Doug Neiner](https://github.com/dcneiner)
* [Jonathan Creamer](https://github.com/jcreamer898)
* [Jordan Kasper](https://github.com/jakerella)

@@ -157,5 +157,14 @@ (function(root, factory) {

// Apply namespace prefix to the mock handler's url.
var namespace = handler.namespace || (typeof(handler.namespace) === 'undefined' && $.mockjaxSettings.namespace);
// Inspect the URL of the request and check if the mock handler's url
// matches the url for this ajax request
if ( $.isFunction(handler.url.test) ) {
// namespace exists prepend handler.url with namespace
if (!!namespace) {
namespace = namespace.replace(/(\/+)$/, '');
var pattern = handler.url.source.replace(/^(\^+)/, '').replace(/^/, '^(' + namespace + ')?\/?');
handler.url = new RegExp(pattern);
}
// The user provided a regex for the url, test it

@@ -167,7 +176,4 @@ if ( !handler.url.test( requestSettings.url ) ) {

var effecitveUrl = handler.url;
var effectiveUrl = handler.url;
// Apply namespace prefix to the mock handler's url.
var namespace = handler.namespace || (typeof(handler.namespace) === 'undefined' && $.mockjaxSettings.namespace);
if (!!namespace) {

@@ -178,9 +184,9 @@ var namespacedUrl = [

].join('/');
effecitveUrl = namespacedUrl;
effectiveUrl = namespacedUrl;
}
// Look for a simple wildcard '*' or a direct URL match
var star = effecitveUrl.indexOf('*');
if (effecitveUrl !== requestSettings.url && star === -1 ||
!new RegExp(effecitveUrl.replace(/[-[\]{}()+?.,\\^$|#\s]/g, '\\$&').replace(/\*/g, '.+')).test(requestSettings.url)) {
var star = effectiveUrl.indexOf('*');
if (effectiveUrl !== requestSettings.url && star === -1 ||
!new RegExp(effectiveUrl.replace(/[-[\]{}()+?.,\\^$|#\s]/g, '\\$&').replace(/\*/g, '.+')).test(requestSettings.url)) {
return null;

@@ -187,0 +193,0 @@ }

'use strict';
var jquery = require('../../lib/jquery-3.4.1.js');
var jquery = require('../../lib/jquery-3.5.1.js');
var mockjax = require('../../src/jquery.mockjax')(jquery, window);

@@ -5,0 +5,0 @@

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

$.mockjaxSettings.namespace = '/api/v1';
$.mockjax({

@@ -30,2 +29,20 @@ url: 'myservice'

t('url (RegExp) should be namespaced via global mockjax settings', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = '/api/v1';
$.mockjax({
url: /^myservice$/
});
$.ajax({
url: '/api/v1/myservice',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
done();
}
});
});
t('should be able to override global namespace per-mock', function(assert) {

@@ -56,3 +73,28 @@ var done = assert.async();

});
t('should be able to override global namespace per-mock (RegExp)', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = '/api/v1';
$.mockjax({
url: /^myservice$/,
namespace: '/api/v2'
});
$.ajax({
url: '/api/v2/myservice',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
$.ajax({
url: '/api/v1/myservice',
error: function() {
assert.ok(true, 'error callback was called');
done();
}
});
}
});
});
t('should not mock a non-matching url within a namespace', function(assert) {

@@ -79,2 +121,23 @@ var done = assert.async();

t('should not mock a non-matching (RegExp) url within a namespace', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = '/api/v1';
$.mockjax({
url: /^myservice$/,
});
$.ajax({
url: '/api/v1/yourservice',
success: function() {
assert.ok(false, 'call should not be successful');
},
error: function() {
assert.ok(true, 'error callback was called');
done();
}
});
});
t('should handle multiple mocks in a row within a namespace', function(assert) {

@@ -109,2 +172,56 @@ var done = assert.async();

t('should handle multiple mocks in a row within a namespace (RegExp)', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = '/api/v1';
$.mockjax({
url: /^one$/,
});
$.mockjax({
url: /^two$/,
});
$.ajax({
url: '/api/v1/one',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
$.ajax({
url: '/api/v1/two',
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
done();
}
});
}
});
});
t('should handle pattern without "^" start character (RegExp)', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = '/api/v1';
$.mockjax({
url: /one|two/,
});
$.ajax({
url: '/api/v1/one',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
$.ajax({
url: '/api/v1/two',
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
done();
}
});
}
});
});
t('should pass the correct url to the response settings', function(assert) {

@@ -132,2 +249,24 @@ var done = assert.async();

t('should pass the correct url to the response settings (RegExp)', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = '/api/v1';
$.mockjax({
url: /^myservice$/,
response: function(settings) {
assert.equal(settings.url, '/api/v1/myservice');
}
});
$.ajax({
url: '/api/v1/myservice',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
done();
}
});
});
t('should handle extra slashes', function(assert) {

@@ -152,2 +291,21 @@ var done = assert.async();

t('should handle extra slashes (RegExp)', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = '/api/v1/';
$.mockjax({
url: /^\/myservice$/,
});
$.ajax({
url: '/api/v1/myservice',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
done();
}
});
});
t('should handle missing slashes', function(assert) {

@@ -172,2 +330,21 @@ var done = assert.async();

t('should handle missing slashes (RegExp)', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = '/api/v1';
$.mockjax({
url: /^myservice$/,
});
$.ajax({
url: '/api/v1/myservice',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
done();
}
});
});
t('should pass url to response settings using http://', function(assert) {

@@ -195,2 +372,24 @@ var done = assert.async();

t('should pass (RegExp) url to response settings using http://', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = 'http://localhost:4000';
$.mockjax({
url: /^myservice$/,
response: function(settings) {
assert.equal(settings.url, 'http://localhost:4000/myservice');
}
});
$.ajax({
url: 'http://localhost:4000/myservice',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
done();
}
});
});
t('should pass http:// url with trailing / to response', function(assert) {

@@ -218,2 +417,24 @@ var done = assert.async();

t('should pass http:// (RegExp) url with trailing / to response', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = 'http://localhost/';
$.mockjax({
url: /^\/myservice$/,
response: function(settings) {
assert.equal(settings.url, 'http://localhost/myservice');
}
});
$.ajax({
url: 'http://localhost/myservice',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
done();
}
});
});
t('should handle the same mock multiple times in a namespace', function(assert) {

@@ -245,2 +466,28 @@ var done = assert.async();

t('should handle the same mock multiple times in a namespace (RegExp)', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = '/api/v1';
$.mockjax({
url: /^one$/,
});
$.ajax({
url: '/api/v1/one',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
$.ajax({
url: '/api/v1/one',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
done();
}
});
}
});
});
t('should be able to declare no namespace on individual mock', function(assert) {

@@ -278,2 +525,34 @@

t('should be able to declare no namespace on individual mock (RegExp)', function(assert) {
var done = assert.async();
$.mockjaxSettings.namespace = '/api/v1';
$.mockjax({
url: /^one$/,
});
$.mockjax({
url: /^\/two$/,
namespace: null
});
$.ajax({
url: '/api/v1/one',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
}
});
$.ajax({
url: '/two',
error: qunit.noErrorCallbackExpected,
complete: function(xhr) {
assert.equal(xhr.status, 200, 'Response was successful');
done();
}
});
});
})(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