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.2.2 to 2.3.0

5

CHANGELOG.md

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

## 2018-01-07 v2.3.0
* Added new `handlers()` method
* Add basic support for 301 and 302 status codes with auto-redirection
* Fix up some README issues
## 2016-09-15 v2.2.2

@@ -2,0 +7,0 @@ * Minor bug fixes having to do with namespacing (thanks @tomeara)

54

dist/jquery.mockjax.js
/*! jQuery Mockjax
* A Plugin providing simple and flexible mocking of ajax requests and responses
*
* Version: 2.2.1
* Version: 2.3.0
* Home: https://github.com/jakerella/jquery-mockjax
* Copyright (c) 2017 Jordan Kasper, formerly appendTo;
* Copyright (c) 2018 Jordan Kasper, formerly appendTo;
* NOTE: This repository was taken over by Jordan Kasper (@jakerella) October, 2014

@@ -177,4 +177,7 @@ *

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

@@ -185,9 +188,9 @@ var namespacedUrl = [

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

@@ -664,3 +667,21 @@ }

if ((mockHandler.status === 301 || mockHandler.status === 302) &&
(requestSettings.type.toUpperCase() === 'GET' || requestSettings.type.toUpperCase() === 'HEAD') &&
mockHandler.headers.Location) {
logger.debug('Doing mock redirect to', mockHandler.headers.Location, requestSettings.type);
var redirectSettings = {};
var origKeys = Object.keys(origSettings);
// We can't alter origSettings, so we need a shallow copy of it...
for (var oi=0; oi<origKeys.length; oi++) {
redirectSettings[origKeys[oi]] = origSettings[origKeys[oi]];
}
redirectSettings.url = mockHandler.headers.Location;
redirectSettings.headers = {
Referer: origSettings.url
};
return handleAjax(redirectSettings);
}
if ( requestSettings.dataType && requestSettings.dataType.toUpperCase() === 'JSONP' ) {

@@ -732,2 +753,3 @@ if ((mockRequest = processJsonpMock( requestSettings, mockHandler, origSettings ))) {

else { // trigger a normal request
logger.log('Real ajax call to', origSettings.url);
return _ajax.apply($, [origSettings]);

@@ -972,2 +994,20 @@ }

/**
* Retrieve the current array of mock handlers.
* NOTE: Altering these handlers, or the array itself is probably not a good
* idea! This could easily lead to malfunction of the library. If you need
* to alter a handler, clear(index) it (using the array index) and then
* create a new handler with $.mockjax({ ... })
*
* **WARNING**: Additionally, note that the handlers array WILL NOT CHANGE
* when a mock is cleared. This is because we have to maintain the handler
* indeces for clearing of other mock handlers. (This is not ideal, and
* will probably change in the future.) Cleared mocks are set to null!
*
* @return {Array} The current collection of handlers
*/
$.mockjax.handlers = function() {
return mockHandlers;
};
/**
* Retrieve all Ajax calls that have been mocked by this library during the

@@ -974,0 +1014,0 @@ * current session (in other words, only since you last loaded this file).

2

dist/jquery.mockjax.min.js

@@ -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");var e=a("parsererror",d);if(1===e.length)throw new Error("Error: "+a(d).text());return d}catch(b){var f=void 0===b.name?b:b.name+": "+b.message;return void a(document).trigger("xmlParseError",[f])}}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;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.namespace||a.mockjaxSettings.namespace;if(e){var f=[e.replace(/(\/+)$/,""),b.url.replace(/^(\/+)/,"")].join("/");b.url=f}var g=b.url.indexOf("*");if(b.url!==c.url&&g===-1||!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];if(d!==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;"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}}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))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;d<g;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;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&&"undefined"!=typeof b.logging&&(e=b.logging),d=0===d?d:d||D.LOG,c=c.splice?c:[c],!(e===!1||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.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;"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),!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});
{
"name": "jquery-mockjax",
"title": "jQuery Mockjax",
"version": "2.2.2",
"version": "2.3.0",
"main": "./src/jquery.mockjax.js",

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

@@ -7,9 +7,5 @@ # jQuery Mockjax: Ajax request mocking #

**Note that we recently switched the `master` branch to version 2!** 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.
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.
jQuery Mockjax provides request/response mocking for ajax requests using the
jQuery API and provides all standard behaviors in the request/response flow.
jQuery Mockjax provides request/response mocking for ajax requests using the jQuery API and provides all standard behaviors in the request/response flow.

@@ -108,3 +104,5 @@ You may report any issues you may find [in the github issue tracking](https://github.com/jakerella/jquery-mockjax/issues).

* `Object $.mockjax.handler(/* Number */ id)`
* Returns the mock request settings for the handler with the provided `id`
* Returns the mock request settings for the handler with the provided `id`. Be careful here, you're accessing the inner workings of the plugin, any changes to this object could be bad.
* `Array $.mockjax.handlers()`
* 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])`

@@ -776,3 +774,3 @@ * 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)

var jquery = require('jquery');
var mockjax = require('jquery.mockjax')(jquery, window);
var mockjax = require('jquery-mockjax')(jquery, window);
// Note that we expect `window` to be defined once this file is browserified and

@@ -779,0 +777,0 @@ // used in a browser. If it isn't Mockjax will have a problem!

@@ -654,3 +654,21 @@ (function(root, factory) {

if ((mockHandler.status === 301 || mockHandler.status === 302) &&
(requestSettings.type.toUpperCase() === 'GET' || requestSettings.type.toUpperCase() === 'HEAD') &&
mockHandler.headers.Location) {
logger.debug('Doing mock redirect to', mockHandler.headers.Location, requestSettings.type);
var redirectSettings = {};
var origKeys = Object.keys(origSettings);
// We can't alter origSettings, so we need a shallow copy of it...
for (var oi=0; oi<origKeys.length; oi++) {
redirectSettings[origKeys[oi]] = origSettings[origKeys[oi]];
}
redirectSettings.url = mockHandler.headers.Location;
redirectSettings.headers = {
Referer: origSettings.url
};
return handleAjax(redirectSettings);
}
if ( requestSettings.dataType && requestSettings.dataType.toUpperCase() === 'JSONP' ) {

@@ -722,2 +740,3 @@ if ((mockRequest = processJsonpMock( requestSettings, mockHandler, origSettings ))) {

else { // trigger a normal request
logger.log('Real ajax call to', origSettings.url);
return _ajax.apply($, [origSettings]);

@@ -962,2 +981,20 @@ }

/**
* Retrieve the current array of mock handlers.
* NOTE: Altering these handlers, or the array itself is probably not a good
* idea! This could easily lead to malfunction of the library. If you need
* to alter a handler, clear(index) it (using the array index) and then
* create a new handler with $.mockjax({ ... })
*
* **WARNING**: Additionally, note that the handlers array WILL NOT CHANGE
* when a mock is cleared. This is because we have to maintain the handler
* indeces for clearing of other mock handlers. (This is not ideal, and
* will probably change in the future.) Cleared mocks are set to null!
*
* @return {Array} The current collection of handlers
*/
$.mockjax.handlers = function() {
return mockHandlers;
};
/**
* Retrieve all Ajax calls that have been mocked by this library during the

@@ -964,0 +1001,0 @@ * current session (in other words, only since you last loaded this file).

@@ -500,2 +500,38 @@ (function(qunit, $) {

t('Inspecting $.mockjax.handlers() for type and length', function(assert) {
assert.ok(Array.isArray($.mockjax.handlers()), 'The list of handlers is an array before any mocks');
assert.strictEqual($.mockjax.handlers().length, 0, 'The list of handlers is empty before any mocks');
$.mockjax({ url: '/foo', responseText: 'Hello Word' });
assert.ok(Array.isArray($.mockjax.handlers()), 'The list of handlers is an array after adding a mock');
assert.strictEqual($.mockjax.handlers().length, 1, 'The length of the list of handlers is correct after adding a mock');
$.mockjax({ url: '/bar', responseText: 'Hello Word' });
$.mockjax({ url: '/bat', responseText: 'Hello Word' });
$.mockjax({ url: '/baz', responseText: 'Hello Word' });
assert.ok(Array.isArray($.mockjax.handlers()), 'The list of handlers is an array after adding many mocks');
assert.strictEqual($.mockjax.handlers().length, 4, 'The length of the list of handlers is correct after adding many mocks');
});
t('Testing $.mockjax.handlers() after clearing', function(assert) {
$.mockjax({ url: '/foo', responseText: 'Hello Word' });
$.mockjax({ url: '/bar', responseText: 'Hello Word' });
$.mockjax({ url: '/bat', responseText: 'Hello Word' });
$.mockjax({ url: '/baz', responseText: 'Hello Word' });
assert.ok(Array.isArray($.mockjax.handlers()), 'The list of handlers is an array after adding mocks');
assert.strictEqual($.mockjax.handlers().length, 4, 'The length of the list of handlers is correct after adding mocks');
$.mockjax.clear(1);
assert.ok(Array.isArray($.mockjax.handlers()), 'The list of handlers is an array after clearing mock');
assert.strictEqual($.mockjax.handlers().length, 4, 'The length of the list of handlers is correct after clearing mock');
assert.strictEqual($.mockjax.handlers()[0].url, '/foo', 'The first handler is correct after clearing');
assert.strictEqual($.mockjax.handlers()[1], null, 'The cleared handler is correct after clearing');
assert.strictEqual($.mockjax.handlers()[3].url, '/baz', 'The last handler is correct after clearing');
});
t('Inspecting $.mockjax() with multiple mocks argument', function(assert) {

@@ -502,0 +538,0 @@ var done = assert.async();

(function(qunit, $) {
'use strict';
var t = qunit.test;
/* -------------------- */
qunit.module( 'Headers' );
/* -------------------- */
t('headers can be inspected via setRequestHeader()', function(assert) {
var done = assert.async();
assert.expect(1);

@@ -21,3 +21,3 @@

var key;
if ('/inspect-headers' === requestSettings.url) {

@@ -46,3 +46,3 @@ return {

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

@@ -64,6 +64,6 @@ url: '/response-callback',

});
t('Setting the content-type', function(assert) {
var done = assert.async();
$.mockjax({

@@ -90,6 +90,6 @@ url: '/response-callback',

});
t('Setting additional HTTP response headers', function(assert) {
var done = assert.async();
$.mockjax({

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

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

@@ -144,3 +144,146 @@ url: '/restful/fortune',

});
})(window.QUnit, window.jQuery);
t('Handle 301 redirect with NO mock set for second location', function(assert) {
var done = assert.async();
$.mockjax({
url: '/redirect-301',
status: 301,
headers: {
'Location': '/foo'
},
responseText: 'done'
});
$.ajax({
url: '/redirect-301',
success: function() {
assert.ok(false, 'Success handler should not have been called');
},
complete: function(xhr) {
assert.strictEqual($.mockjax.unmockedAjaxCalls().length, 1, 'We have an unmocked call');
assert.strictEqual($.mockjax.unmockedAjaxCalls()[0].url, '/foo', 'We have the correct unmocked call');
assert.strictEqual(xhr.getResponseHeader('Location'), null, 'Location header should now be null');
assert.strictEqual(xhr.status, 404, 'response status matches');
done();
}
});
});
t('Handle 302 redirect with NO mock set for second location', function(assert) {
var done = assert.async();
$.mockjax({
url: '/redirect-302',
status: 302,
headers: {
'Location': '/foo'
},
responseText: 'done'
});
$.ajax({
url: '/redirect-302',
success: function() {
assert.ok(false, 'Success handler should not have been called');
},
complete: function(xhr) {
assert.strictEqual($.mockjax.unmockedAjaxCalls().length, 1, 'We have an unmocked call');
assert.strictEqual($.mockjax.unmockedAjaxCalls()[0].url, '/foo', 'We have the correct unmocked call');
assert.strictEqual(xhr.getResponseHeader('Location'), null, 'Location header should now be null');
assert.strictEqual(xhr.status, 404, 'response status matches');
done();
}
});
});
t('Handle 301 redirect with another mock set for second location', function(assert) {
var done = assert.async();
$.mockjax({
url: '/redirect-301',
status: 301,
headers: {
'Location': '/foo'
},
responseText: 'done'
});
$.mockjax({
url: '/foo',
responseText: 'bar'
});
$.ajax({
url: '/redirect-301',
success: function(res, status, xhr) {
assert.strictEqual(res, 'bar', 'The response text is correct');
assert.strictEqual(xhr.status, 200, 'The response status is correct');
},
error: qunit.noErrorCallbackExpected,
complete: done
});
});
t('Should not redirect on 301 without Location header', function(assert) {
var done = assert.async();
$.mockjax({
url: '/redirect-301',
status: 301,
headers: {
'X-Foobar': '/foo'
},
responseText: 'done'
});
$.mockjax({
url: '/foo',
responseText: 'bar'
});
$.ajax({
url: '/redirect-301',
success: function() {
assert.ok(false, 'Success handler should not have been called');
},
complete: function(xhr) {
assert.strictEqual(xhr.status, 301, 'response status matches');
done();
}
});
});
t('Should not redirect on POST request', function(assert) {
var done = assert.async();
$.mockjax({
url: '/redirect-301',
status: 301,
type: 'POST',
headers: {
'Location': '/foo'
},
responseText: 'done'
});
$.mockjax({
url: '/foo',
type: 'POST',
responseText: 'bar'
});
$.ajax({
url: '/redirect-301',
type: 'POST',
success: function() {
assert.ok(false, 'Success handler should not have been called');
},
complete: function(xhr) {
assert.strictEqual(xhr.status, 301, 'response status matches');
done();
}
});
});
})(window.QUnit, window.jQuery);
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