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

jasmine-ajax

Package Overview
Dependencies
Maintainers
2
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

jasmine-ajax - npm Package Compare versions

Comparing version 2.0.1 to 2.0.2

spec/fakeRequestSpec.js

2

bower.json

@@ -12,3 +12,3 @@ {

"dependencies": {
"jasmine" : "2.0.0"
"jasmine" : "~2.0"
},

@@ -15,0 +15,0 @@ "moduleType": [

@@ -26,9 +26,14 @@ module.exports = function( grunt ) {

jasmine: false,
ajaxRequests: true,
ajaxStubs: true,
module: false,
exports: true
exports: true,
describe: false,
it: false,
expect: false,
beforeEach: false,
afterEach: false,
spyOn: false,
getJasmineRequireObj: false
}
},
all: ['Gruntfile.js', 'lib/*.js', 'spec/*.js']
all: ['Gruntfile.js', 'src/**/*.js', 'lib/**/*.js', 'spec/**/*.js']
},

@@ -39,2 +44,13 @@ shell: {

}
},
concat: {
mockAjax: {
src: [
'src/requireAjax.js',
'src/**/*.js',
'!src/boot.js',
'src/boot.js'
],
dest: 'lib/mock-ajax.js'
}
}

@@ -44,2 +60,3 @@ });

grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-shell');

@@ -46,0 +63,0 @@

@@ -33,3 +33,16 @@ /*

(function() {
getJasmineRequireObj().ajax = function(jRequire) {
var $ajax = {};
$ajax.RequestStub = jRequire.AjaxRequestStub();
$ajax.RequestTracker = jRequire.AjaxRequestTracker();
$ajax.StubTracker = jRequire.AjaxStubTracker();
$ajax.ParamParser = jRequire.AjaxParamParser();
$ajax.fakeRequest = jRequire.AjaxFakeRequest();
$ajax.MockAjax = jRequire.MockAjax($ajax);
return $ajax.MockAjax;
};
getJasmineRequireObj().AjaxFakeRequest = function() {
function extend(destination, source, propertiesToSkip) {

@@ -54,126 +67,83 @@ propertiesToSkip = propertiesToSkip || [];

function MockAjax(global) {
var requestTracker = new RequestTracker(),
stubTracker = new StubTracker(),
paramParser = new ParamParser(),
realAjaxFunction = global.XMLHttpRequest,
mockAjaxFunction = fakeRequest(requestTracker, stubTracker, paramParser);
this.install = function() {
global.XMLHttpRequest = mockAjaxFunction;
};
this.uninstall = function() {
global.XMLHttpRequest = realAjaxFunction;
this.stubs.reset();
this.requests.reset();
paramParser.reset();
};
this.stubRequest = function(url, data) {
var stub = new RequestStub(url, data);
stubTracker.addStub(stub);
return stub;
};
this.withMock = function(closure) {
this.install();
try {
closure();
} finally {
this.uninstall();
function wrapProgressEvent(xhr, eventName) {
return function() {
if (xhr[eventName]) {
xhr[eventName]();
}
};
}
this.addCustomParamParser = function(parser) {
paramParser.add(parser);
function initializeEvents(xhr) {
return {
'loadstart': wrapProgressEvent(xhr, 'onloadstart'),
'load': wrapProgressEvent(xhr, 'onload'),
'loadend': wrapProgressEvent(xhr, 'onloadend'),
'progress': wrapProgressEvent(xhr, 'onprogress'),
'error': wrapProgressEvent(xhr, 'onerror'),
'abort': wrapProgressEvent(xhr, 'onabort'),
'timeout': wrapProgressEvent(xhr, 'ontimeout')
};
this.requests = requestTracker;
this.stubs = stubTracker;
}
function StubTracker() {
var stubs = [];
function fakeRequest(global, requestTracker, stubTracker, paramParser) {
function FakeXMLHttpRequest() {
requestTracker.track(this);
this.events = initializeEvents(this);
this.requestHeaders = {};
this.overriddenMimeType = null;
}
this.addStub = function(stub) {
stubs.push(stub);
};
this.reset = function() {
stubs = [];
};
this.findStub = function(url, data) {
for (var i = stubs.length - 1; i >= 0; i--) {
var stub = stubs[i];
if (stub.matches(url, data)) {
return stub;
function findHeader(name, headers) {
name = name.toLowerCase();
for (var header in headers) {
if (header.toLowerCase() === name) {
return headers[header];
}
}
};
}
}
function ParamParser() {
var defaults = [
{
test: function(xhr) {
return /^application\/json/.test(xhr.contentType());
},
parse: function jsonParser(paramString) {
return JSON.parse(paramString);
}
},
{
test: function(xhr) {
return true;
},
parse: function naiveParser(paramString) {
var data = {};
var params = paramString.split('&');
function normalizeHeaders(rawHeaders, contentType) {
var headers = [];
for (var i = 0; i < params.length; ++i) {
var kv = params[i].replace(/\+/g, ' ').split('=');
var key = decodeURIComponent(kv[0]);
data[key] = data[key] || [];
data[key].push(decodeURIComponent(kv[1]));
if (rawHeaders) {
if (rawHeaders instanceof Array) {
headers = rawHeaders;
} else {
for (var headerName in rawHeaders) {
if (rawHeaders.hasOwnProperty(headerName)) {
headers.push({ name: headerName, value: rawHeaders[headerName] });
}
}
return data;
}
} else {
headers.push({ name: "Content-Type", value: contentType || "application/json" });
}
];
var paramParsers = [];
this.add = function(parser) {
paramParsers.unshift(parser);
};
return headers;
}
this.findParser = function(xhr) {
for(var i in paramParsers) {
var parser = paramParsers[i];
if (parser.test(xhr)) {
return parser;
}
}
};
this.reset = function() {
paramParsers = [];
for(var i in defaults) {
paramParsers.push(defaults[i]);
function parseXml(xmlText, contentType) {
if (global.DOMParser) {
return (new global.DOMParser()).parseFromString(xmlText, 'text/xml');
} else {
var xml = new global.ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(xmlText);
return xml;
}
};
}
this.reset();
}
var xmlParsables = ['text/xml', 'application/xml'];
function fakeRequest(requestTracker, stubTracker, paramParser) {
function FakeXMLHttpRequest() {
requestTracker.track(this);
this.requestHeaders = {};
function getResponseXml(responseText, contentType) {
if (arrayContains(xmlParsables, contentType.toLowerCase())) {
return parseXml(responseText, contentType);
} else if (contentType.match(/\+xml$/)) {
return parseXml(responseText, 'text/xml');
}
return null;
}
var iePropertiesThatCannotBeCopied = ['responseBody', 'responseText', 'responseXML', 'status', 'statusText', 'responseTimeout'];
extend(FakeXMLHttpRequest.prototype, new window.XMLHttpRequest(), iePropertiesThatCannotBeCopied);
extend(FakeXMLHttpRequest.prototype, new global.XMLHttpRequest(), iePropertiesThatCannotBeCopied);
extend(FakeXMLHttpRequest.prototype, {

@@ -190,5 +160,13 @@ open: function() {

setRequestHeader: function(header, value) {
this.requestHeaders[header] = value;
if(this.requestHeaders.hasOwnProperty(header)) {
this.requestHeaders[header] = [this.requestHeaders[header], value].join(', ');
} else {
this.requestHeaders[header] = value;
}
},
overrideMimeType: function(mime) {
this.overriddenMimeType = mime;
},
abort: function() {

@@ -199,2 +177,5 @@ this.readyState = 0;

this.onreadystatechange();
this.events.progress();
this.events.abort();
this.events.loadend();
},

@@ -204,4 +185,9 @@

onload: function() {
},
onloadstart: null,
onprogress: null,
onabort: null,
onerror: null,
onload: null,
ontimeout: null,
onloadend: null,

@@ -211,2 +197,12 @@ onreadystatechange: function(isTimeout) {

addEventListener: function(event, callback) {
var existingCallback = this.events[event],
self = this;
this.events[event] = function() {
callback.apply(self);
existingCallback();
};
},
status: null,

@@ -217,5 +213,6 @@

this.readyState = 2;
this.events.loadstart();
this.onreadystatechange();
var stub = stubTracker.findStub(this.url, data);
var stub = stubTracker.findStub(this.url, data, this.method);
if (stub) {

@@ -227,7 +224,3 @@ this.response(stub);

contentType: function() {
for (var header in this.requestHeaders) {
if (header.toLowerCase() === 'content-type') {
return this.requestHeaders[header];
}
}
return findHeader('content-type', this.requestHeaders);
},

@@ -244,3 +237,15 @@

getResponseHeader: function(name) {
return this.responseHeaders[name];
name = name.toLowerCase();
var resultHeader;
for(var i = 0; i < this.responseHeaders.length; i++) {
var header = this.responseHeaders[i];
if (name === header.name.toLowerCase()) {
if (resultHeader) {
resultHeader = [resultHeader, header.value].join(', ');
} else {
resultHeader = header.value;
}
}
}
return resultHeader;
},

@@ -250,6 +255,5 @@

var responseHeaders = [];
for (var i in this.responseHeaders) {
if (this.responseHeaders.hasOwnProperty(i)) {
responseHeaders.push(i + ': ' + this.responseHeaders[i]);
}
for (var i = 0; i < this.responseHeaders.length; i++) {
responseHeaders.push(this.responseHeaders[i].name + ': ' +
this.responseHeaders[i].value);
}

@@ -262,2 +266,5 @@ return responseHeaders.join('\r\n');

response: function(response) {
if (this.readyState === 4) {
throw new Error("FakeXMLHttpRequest already completed");
}
this.status = response.status;

@@ -267,13 +274,32 @@ this.statusText = response.statusText || "";

this.readyState = 4;
this.responseHeaders = response.responseHeaders ||
{"Content-Type": response.contentType || "application/json" };
this.responseHeaders = normalizeHeaders(response.responseHeaders, response.contentType);
this.responseXML = getResponseXml(response.responseText, this.getResponseHeader('content-type') || '');
this.onload();
this.onreadystatechange();
this.events.progress();
this.events.load();
this.events.loadend();
},
responseTimeout: function() {
if (this.readyState === 4) {
throw new Error("FakeXMLHttpRequest already completed");
}
this.readyState = 4;
jasmine.clock().tick(30000);
this.onreadystatechange('timeout');
this.events.progress();
this.events.timeout();
this.events.loadend();
},
responseError: function() {
if (this.readyState === 4) {
throw new Error("FakeXMLHttpRequest already completed");
}
this.readyState = 4;
this.onreadystatechange();
this.events.progress();
this.events.error();
this.events.loadend();
}

@@ -285,2 +311,152 @@ });

return fakeRequest;
};
getJasmineRequireObj().MockAjax = function($ajax) {
function MockAjax(global) {
var requestTracker = new $ajax.RequestTracker(),
stubTracker = new $ajax.StubTracker(),
paramParser = new $ajax.ParamParser(),
realAjaxFunction = global.XMLHttpRequest,
mockAjaxFunction = $ajax.fakeRequest(global, requestTracker, stubTracker, paramParser);
this.install = function() {
global.XMLHttpRequest = mockAjaxFunction;
};
this.uninstall = function() {
global.XMLHttpRequest = realAjaxFunction;
this.stubs.reset();
this.requests.reset();
paramParser.reset();
};
this.stubRequest = function(url, data, method) {
var stub = new $ajax.RequestStub(url, data, method);
stubTracker.addStub(stub);
return stub;
};
this.withMock = function(closure) {
this.install();
try {
closure();
} finally {
this.uninstall();
}
};
this.addCustomParamParser = function(parser) {
paramParser.add(parser);
};
this.requests = requestTracker;
this.stubs = stubTracker;
}
return MockAjax;
};
getJasmineRequireObj().AjaxParamParser = function() {
function ParamParser() {
var defaults = [
{
test: function(xhr) {
return (/^application\/json/).test(xhr.contentType());
},
parse: function jsonParser(paramString) {
return JSON.parse(paramString);
}
},
{
test: function(xhr) {
return true;
},
parse: function naiveParser(paramString) {
var data = {};
var params = paramString.split('&');
for (var i = 0; i < params.length; ++i) {
var kv = params[i].replace(/\+/g, ' ').split('=');
var key = decodeURIComponent(kv[0]);
data[key] = data[key] || [];
data[key].push(decodeURIComponent(kv[1]));
}
return data;
}
}
];
var paramParsers = [];
this.add = function(parser) {
paramParsers.unshift(parser);
};
this.findParser = function(xhr) {
for(var i in paramParsers) {
var parser = paramParsers[i];
if (parser.test(xhr)) {
return parser;
}
}
};
this.reset = function() {
paramParsers = [];
for(var i in defaults) {
paramParsers.push(defaults[i]);
}
};
this.reset();
}
return ParamParser;
};
getJasmineRequireObj().AjaxRequestStub = function() {
function RequestStub(url, stubData, method) {
var normalizeQuery = function(query) {
return query ? query.split('&').sort().join('&') : undefined;
};
if (url instanceof RegExp) {
this.url = url;
this.query = undefined;
} else {
var split = url.split('?');
this.url = split[0];
this.query = split.length > 1 ? normalizeQuery(split[1]) : undefined;
}
this.data = normalizeQuery(stubData);
this.method = method;
this.andReturn = function(options) {
this.status = options.status || 200;
this.contentType = options.contentType;
this.responseText = options.responseText;
};
this.matches = function(fullUrl, data, method) {
var matches = false;
fullUrl = fullUrl.toString();
if (this.url instanceof RegExp) {
matches = this.url.test(fullUrl);
} else {
var urlSplit = fullUrl.split('?'),
url = urlSplit[0],
query = urlSplit[1];
matches = this.url === url && this.query === normalizeQuery(query);
}
return matches && (!this.data || this.data === normalizeQuery(data)) && (!this.method || this.method === method);
};
}
return RequestStub;
};
getJasmineRequireObj().AjaxRequestTracker = function() {
function RequestTracker() {

@@ -314,3 +490,2 @@ var requests = [];

this.filter = function(url_to_match) {
if (requests.length == 0) return [];
var matching_requests = [];

@@ -326,3 +501,3 @@

} else {
if (requests[i].url == url_to_match) {
if (requests[i].url === url_to_match) {
matching_requests.push(requests[i]);

@@ -337,40 +512,33 @@ }

function RequestStub(url, stubData) {
var normalizeQuery = function(query) {
return query ? query.split('&').sort().join('&') : undefined;
};
return RequestTracker;
};
if (url instanceof RegExp) {
this.url = url;
this.query = undefined;
} else {
var split = url.split('?');
this.url = split[0];
this.query = split.length > 1 ? normalizeQuery(split[1]) : undefined;
}
getJasmineRequireObj().AjaxStubTracker = function() {
function StubTracker() {
var stubs = [];
this.data = normalizeQuery(stubData);
this.addStub = function(stub) {
stubs.push(stub);
};
this.andReturn = function(options) {
this.status = options.status || 200;
this.contentType = options.contentType;
this.responseText = options.responseText;
this.reset = function() {
stubs = [];
};
this.matches = function(fullUrl, data) {
var matches = false;
fullUrl = fullUrl.toString();
if (this.url instanceof RegExp) {
matches = this.url.test(fullUrl);
} else {
var urlSplit = fullUrl.split('?'),
url = urlSplit[0],
query = urlSplit[1];
matches = this.url === url && this.query === normalizeQuery(query);
this.findStub = function(url, data, method) {
for (var i = stubs.length - 1; i >= 0; i--) {
var stub = stubs[i];
if (stub.matches(url, data, method)) {
return stub;
}
}
return matches && (!this.data || this.data === normalizeQuery(data));
};
}
return StubTracker;
};
(function() {
var jRequire = getJasmineRequireObj(),
MockAjax = jRequire.ajax(jRequire);
if (typeof window === "undefined" && typeof exports === "object") {

@@ -377,0 +545,0 @@ exports.MockAjax = MockAjax;

@@ -6,3 +6,3 @@ {

"main": "lib/mock-ajax.js",
"version": "2.0.1",
"version": "2.0.2",
"private": false,

@@ -17,2 +17,4 @@ "license": "MIT",

"grunt": "0.4.0",
"grunt-cli": "~0.1.13",
"grunt-contrib-concat": "~0.5.0",
"grunt-contrib-jshint": "~0.1.1",

@@ -19,0 +21,0 @@ "grunt-shell": "~0.2.1"

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

Sorry, the diff of this file is not supported yet

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