Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

jquery-mockjax

Package Overview
Dependencies
Maintainers
3
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jquery-mockjax - npm Package Compare versions

Comparing version 2.4.0 to 2.5.0

browserstack-config.js

7

CHANGELOG.md

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

## 2018-07-29 v2.5.0
* Added support for ignoring test files in the automated runs; this was necessary
because Browserstack does something weird with the console and it causes
the logging tests to timeout
* Fixed Browserstack automated runs by ignoring logging tests
* Added an option to reverse the mock handler priority order (thanks @addepar-andy)
## 2018-06-17 v2.4.0

@@ -2,0 +9,0 @@ * Added support for an array of status codes in mocked response (thanks @reinrl)

18

CONTRIBUTING.md

@@ -117,7 +117,15 @@ # Contributing to Mockjax #

Lastly, we'd like you to run your tests on as many browsers as possible. Check the
main [README](README.md#browsers-tested) file for the browsers we support. If you
don't have access to one of those browsers, try running the tests using a virtual
machine or via a service like [BrowserStack](http://www.browserstack.com),
[Sauce Labs](https://saucelabs.com), or [Modern.IE](https://www.modern.ie).
main [README](README.md#browsers-tested) file for the browsers we support.
We highly recommend running your tests in a virtual environment to capture any issues
in specific browsers. You can do so easily with out BrowserStack integration. In
fact, all of our tests will run on BrowserStack's platform for all supported
browsers when you submit a PR to `master`. That said, you can run these on your
own using the command below. All you need to do is set the `BROWSERSTACK_KEY`
environment variable first! Now run this in your terminal:
```shell
~$ node browserstack.js
```
## Be sure to generate a build!

@@ -138,3 +146,3 @@

You should also write a good PR message with information on why this feature or fix is
necesary or a good idea. For features, be sure to include information on _how to use_
necessary or a good idea. For features, be sure to include information on _how to use_
the feature; and for bugs, information on how to reproduce the bug is helpful!

@@ -141,0 +149,0 @@

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

@@ -646,12 +646,14 @@ * Copyright (c) 2018 Jordan Kasper, formerly appendTo;

// Iterate over our mock handlers (in registration order) until we find
// one that is willing to intercept the request
// Iterate over our mock handlers (in order depending on the matchInRegistrationOrder setting)
// until we find one that is willing to intercept the request
for(var k = 0; k < mockHandlers.length; k++) {
if ( !mockHandlers[k] ) {
var handlerIndex = $.mockjaxSettings.matchInRegistrationOrder ? k : mockHandlers.length - 1 - k;
var origHandler = mockHandlers[handlerIndex];
if ( !origHandler ) {
continue;
}
mockHandler = getMockForRequest( mockHandlers[k], requestSettings );
mockHandler = getMockForRequest( origHandler, requestSettings );
if(!mockHandler) {
logger.debug( mockHandlers[k], ['Mock does not match request', url, requestSettings] );
logger.debug( origHandler, ['Mock does not match request', url, requestSettings] );
// No valid mock found for this request

@@ -741,3 +743,3 @@ continue;

}));
})(mockHandler, requestSettings, origSettings, mockHandlers[k]);
})(mockHandler, requestSettings, origSettings, origHandler);
/* jshint loopfunc:false */

@@ -887,3 +889,5 @@

* For individual mock handler settings, please see the README on the repo:
* https://github.com/jakerella/jquery-mockjax#api-methods
* https://github.com/jakerella/jquery-mockjax#api-methods.
* For Global settings see:
* https://github.com/jakerella/jquery-mockjax#globally-defining-mockjax-settings
*

@@ -897,2 +901,3 @@ * @type {Object}

logLevelMethods: ['error', 'warn', 'info', 'log', 'debug'],
matchInRegistrationOrder: true,
namespace: null,

@@ -899,0 +904,0 @@ status: 200,

@@ -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++)if(w[i]){if(f=g(w[i],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 j={},m=Object.keys(c),n=0;n<m.length;n++)j[m[n]]=c[m[n]];return j.url=f.headers.Location,j.headers={Referer:c.url},s(j)}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,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),!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"],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(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});

@@ -9,164 +9,13 @@

/* jshint ignore:start */
/* This is used in an await statement, which apaprently JSHint doesn't like */
var PORT = 4000;
/* jshint ignore:end */
// Project configuration
grunt.initConfig({
// Metadata
pkg: grunt.file.readJSON('package.json'),
var config = require('./grunt-config-options');
config.pkg = grunt.file.readJSON('package.json');
banner: [
'/*! <%= pkg.title || pkg.name %>',
' * A Plugin providing simple and flexible mocking of ajax requests and responses',
' * ',
' * Version: <%= pkg.version %>',
' * Home: <%= pkg.homepage %>',
' * Copyright (c) <%= grunt.template.today("yyyy") %> Jordan Kasper, formerly appendTo;',
' * NOTE: This repository was taken over by Jordan Kasper (@jakerella) October, 2014',
' * ',
' * Dual licensed under the MIT or GPL licenses.',
' * http://opensource.org/licenses/MIT OR http://www.gnu.org/licenses/gpl-2.0.html',
' */\n'
].join('\n'),
grunt.initConfig(config);
// Task configuration
concat: {
options: {
banner: '<%= banner %>',
stripBanners: true
},
dist: {
src: ['./src/jquery.mockjax.js'],
dest: './dist/jquery.mockjax.js'
}
},
uglify: {
options: {
preserveComments: 'some',
},
dist: {
src: './dist/jquery.mockjax.js',
dest: './dist/jquery.mockjax.min.js'
}
},
jshint: {
options: {
jshintrc: true
},
all: [
'src/**/*.js',
'Gruntfile.js',
'test/test.js',
'test/requirejs/*.js',
'test/nodejs/*.js',
'test/browserify/main.js',
'test/browserify/test.js'
]
},
connect: {
server: {
options: {
port: PORT,
base: '.'
}
}
},
qunit: {
// NOTE: these tests are all run by the `test` task below to run against each jQuery version supported
all: []
},
test: {
all: {
jQueryVersions: [
'1.5.2',
'1.6.4',
'1.7.2',
'1.8.3',
'1.9.1',
'1.10.2',
'1.11.3',
'1.12.4',
'2.0.3',
'2.1.4',
'2.2.4',
'3.0.0',
'3.1.1',
'3.2.1',
'3.3.1'
]
},
requirejs: {
jQueryVersions: [
'1.7.2',
'1.8.3',
'1.9.1',
'1.12.4',
'2.2.4',
'3.3.1'
]
},
latestInBranch: {
jQueryVersions: [
'1.12.4',
'2.2.4',
'3.3.1'
]
},
oldestAndLatest: {
jQueryVersions: [
'1.5.2',
'1.12.4',
'2.2.4',
'3.3.1'
]
},
edge: {
jQueryVersions: ['git']
},
dist: {
file: 'dist-min.html',
jQueryVersions: [
'1.5.2',
'1.6.4',
'1.7.2',
'1.8.3',
'1.9.1',
'1.10.2',
'1.11.3',
'1.12.4',
'2.0.3',
'2.1.4',
'2.2.4',
'3.0.0',
'3.1.1',
'3.2.1',
'3.3.1'
]
},
browserify: {
file: 'browserify/index.html',
jQueryVersions: ['not-applicable']
}
},
mochaTest: {
nodejs: {
src: ['./test/nodejs/*.js']
}
},
browserify: {
test: {
src: 'test/browserify/main.js',
dest: 'test/browserify/bundle.js'
}
},
watch: {
gruntfile: {
files: './Gruntfile.js'
},
source: {
files: './src/*.js',
tasks: ['jshint', 'test:latestInBranch']
}
}
});
require('load-grunt-tasks')(grunt);

@@ -182,28 +31,6 @@

var done = this.async();
var i;
var i, l,
baseURL = 'http://localhost:' + PORT,
versionUrls = [],
testFiles = arguments[1] || null,
source = arguments[0] || 'all',
versions = grunt.config.get('test' + ('.' + source) + '.jQueryVersions') || [],
file = grunt.config.get('test' + ('.' + source) + '.file') || 'index.html';
var versionUrls = require('./test/build-version-urls')(grunt.config, arguments[0], arguments[1], arguments[2]);
if (arguments[0] === 'version' && arguments[1]) {
versions = [arguments[1]];
testFiles = (arguments[2]) ? arguments[2] : null;
}
if (testFiles) {
testFiles = JSON.stringify(testFiles.split(/\,/));
}
for (i=0, l=versions.length; i<l; ++i) {
if (arguments[0] === 'requirejs') {
versionUrls.push(baseURL + '/test/requirejs/' + file + '?jquery=' + versions[i] + '&testFiles=' + testFiles);
} else {
versionUrls.push(baseURL + '/test/' + file + '?jquery=' + versions[i] + '&testFiles=' + testFiles);
}
}
console.log(versionUrls);

@@ -210,0 +37,0 @@ for (i=0; i<versionUrls.length; ++i) {

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

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

"scripts": {
"test": "grunt test:all"
"test": "grunt test:all && node browserstack.js"
},

@@ -58,2 +58,3 @@ "keywords": [

"browserify": "^13.1.0",
"browserstack-runner": "^0.7.0",
"grunt": "^1.0.1",

@@ -60,0 +61,0 @@ "grunt-browserify": "^5.0.0",

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

[![Travis CI Badge](https://travis-ci.org/jakerella/jquery-mockjax.svg?branch=master)](https://travis-ci.org/jakerella/jquery-mockjax)
[![BrowserStack Status](https://www.browserstack.com/automate/badge.svg?badge_key=REpZNzZpeWkzMTY2dERuTkkyYVpnTmM1SmZKMGE5cjdVNEVZNjNYelk3ND0tLXpsRGJjaTNhM0RYNnZoVjU2QXVCRnc9PQ==--7bb0e1bf6af34ba1b15703463673c619b1daf292)](https://www.browserstack.com/automate/public-build/REpZNzZpeWkzMTY2dERuTkkyYVpnTmM1SmZKMGE5cjdVNEVZNjNYelk3ND0tLXpsRGJjaTNhM0RYNnZoVjU2QXVCRnc9PQ==--7bb0e1bf6af34ba1b15703463673c619b1daf292)

@@ -733,2 +734,31 @@ 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.

### Globally defining match order
By default, Mockjax matches requests in registration order (mockjax considers
the handlers registered first before handlers registered last). To reverse this
behavior:
```javascript
$.mockjaxSettings.matchInRegistrationOrder = false;
```
Setting `matchInRegistrationOrder` to `false` lets you override previously defined
handlers. Suppose you had:
```javascript
$.mockjax({
url: "/rest",
responseText: "hello"
});
$.mockjax({
url: "/rest",
responseText: "byebye"
});
```
The default behavior is that Mockjax returns `"hello"`, but with `matchInRegistrationOrder`
set to `false`, Mockjax would return `"byebye"`.
This behavior allows you to override older handlers after they are initially set.
### Removing Mockjax Handlers ###

@@ -760,3 +790,3 @@

minor (and major) versions of jQuery beginning with 1.5.2 going all the way
through 2.x. In other words, we don't test 1.6.1, but rather 1.6.4 (the furthest
through 3.x. In other words, we don't test 1.6.1, but rather 1.6.4 (the furthest
patch version on the 1.6.x line). The QUnit tests in the `/test` directory include

@@ -767,14 +797,15 @@ links to each version of jQuery tested in the header.

We use virtual machines to test current versions of the browsers below. In addition,
we test the specific versions of IE specified.
We use [BrowserStack](https://www.browserstack.com)'s awesome open source
collaboration to test Mockjax in real browsers using VMs on their platform. We
run all of our tests on the current versions of the major browsers below, plus
the specific versions of Internet Explorer specified.
* Internet Explorer 8-11
* Edge
* Firefox
* Chrome
* Safari
* Chrome
* Internet Explorer 9-11
_Please note that while we strive to keep `master` as bug free as possible, we do
not necessarily run tests in all of the above browsers for every single commit. We
do, however, ensure all tests are passing before tagging a release._
Each PR will run these tests using TravisCI for continuous integration before
code is merged into master to ensure we do not introduce regressions.

@@ -781,0 +812,0 @@

@@ -635,12 +635,14 @@ (function(root, factory) {

// Iterate over our mock handlers (in registration order) until we find
// one that is willing to intercept the request
// Iterate over our mock handlers (in order depending on the matchInRegistrationOrder setting)
// until we find one that is willing to intercept the request
for(var k = 0; k < mockHandlers.length; k++) {
if ( !mockHandlers[k] ) {
var handlerIndex = $.mockjaxSettings.matchInRegistrationOrder ? k : mockHandlers.length - 1 - k;
var origHandler = mockHandlers[handlerIndex];
if ( !origHandler ) {
continue;
}
mockHandler = getMockForRequest( mockHandlers[k], requestSettings );
mockHandler = getMockForRequest( origHandler, requestSettings );
if(!mockHandler) {
logger.debug( mockHandlers[k], ['Mock does not match request', url, requestSettings] );
logger.debug( origHandler, ['Mock does not match request', url, requestSettings] );
// No valid mock found for this request

@@ -730,3 +732,3 @@ continue;

}));
})(mockHandler, requestSettings, origSettings, mockHandlers[k]);
})(mockHandler, requestSettings, origSettings, origHandler);
/* jshint loopfunc:false */

@@ -876,3 +878,5 @@

* For individual mock handler settings, please see the README on the repo:
* https://github.com/jakerella/jquery-mockjax#api-methods
* https://github.com/jakerella/jquery-mockjax#api-methods.
* For Global settings see:
* https://github.com/jakerella/jquery-mockjax#globally-defining-mockjax-settings
*

@@ -886,2 +890,3 @@ * @type {Object}

logLevelMethods: ['error', 'warn', 'info', 'log', 'debug'],
matchInRegistrationOrder: true,
namespace: null,

@@ -888,0 +893,0 @@ status: 200,

@@ -7,2 +7,3 @@

parts = document.location.search.match( /testFiles=([^&]+)/ ),
ignore = document.location.search.match( /ignoreFiles=([^&]+)/ ),
testFiles = [

@@ -14,2 +15,3 @@ 'core', // This will become: <script src='test-core.js'></script>

'url-match',
'match-ordering',
'headers',

@@ -27,3 +29,6 @@ 'mock-clearing',

try {
testFiles = JSON.parse( decodeURIComponent(parts[ 1 ]) ) || testFiles;
var inputFiles = JSON.parse( decodeURIComponent(parts[ 1 ]) ) || null;
if (inputFiles && inputFiles.length && inputFiles[0] !== 'all') {
testFiles = inputFiles;
}
} catch(err) {

@@ -35,2 +40,15 @@ console.warn('\n WARNING: Unable to parse the test modules you wanted:', err);

if ( ignore && ignore[1] ) {
try {
var ignoreFiles = JSON.parse( decodeURIComponent(ignore[ 1 ]) ) || null;
if (ignoreFiles && ignoreFiles.length) {
testFiles = testFiles.filter(function(file) {
return ignoreFiles.indexOf(file) === -1;
});
}
} catch(err) {
console.warn('\n WARNING: Unable to parse the test modules you wanted to ignore:', err);
}
}
for ( i=0, l = testFiles.length; i<l; i++ ) {

@@ -37,0 +55,0 @@ document.write( '<script src="test-' + testFiles[ i ] + '.js"></script>' );

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc