Starting tests for jQuery version of the Ajax mock.

This commit is contained in:
Davis W. Frank, dwfrank & Hunter Gillane 2010-09-16 15:46:55 -07:00
parent 2d527a5d78
commit c129ed0675
7 changed files with 380 additions and 59 deletions

View File

@ -1,22 +0,0 @@
var xhrs, xhrSpy; // xhr_helper.js
beforeEach(function() {
window.location.hash = "";
$('#jasmine_content').empty();
$('#jasmine_content').html('<div id="store"></div><div id="overlay_spinner"></div>');
// jquery 1.3.x for Ajax
jasmine.Clock.useMock();
// delete window.store;
// window.store = new Store();
spyOn($, 'ajax').andCallThrough();
xhrs = [];
xhrSpy = spyOn(jQuery.ajaxSettings, 'xhr');
xhrSpy.andCallFake(function() {
var newXhr = stubXhr();
xhrs.push(newXhr);
return newXhr;
});
});

View File

@ -1,20 +1,20 @@
function decodeParams(string) { //function decodeParams(string) {
var keyValuePairs = string.replace(/\+/g, "%20").split("&"); // var keyValuePairs = string.replace(/\+/g, "%20").split("&");
var hash = {}; // var hash = {};
$(keyValuePairs).each(function () { // $(keyValuePairs).each(function () {
var equalSplit = this.split("="); // var equalSplit = this.split("=");
var key = decodeURIComponent(equalSplit[0]); // var key = decodeURIComponent(equalSplit[0]);
if (hash[key] == null) { // if (hash[key] == null) {
hash[key] = decodeURIComponent(equalSplit[1]); // hash[key] = decodeURIComponent(equalSplit[1]);
} else if (jQuery.isArray(hash[key])) { // } else if (jQuery.isArray(hash[key])) {
hash[key].push(decodeURIComponent(equalSplit[1])); // hash[key].push(decodeURIComponent(equalSplit[1]));
} else { // } else {
hash[key] = [hash[key]]; // hash[key] = [hash[key]];
hash[key].push(decodeURIComponent(equalSplit[1])); // hash[key].push(decodeURIComponent(equalSplit[1]));
} // }
}); // });
return hash; // return hash;
} //}
// function replaceNextXhr(xhrHash) { // function replaceNextXhr(xhrHash) {
// xhrSpy.andCallFake(function() { // xhrSpy.andCallFake(function() {
@ -31,37 +31,39 @@ function stubXhr(options) {
xhr.method = arguments[0]; xhr.method = arguments[0];
xhr.url = arguments[1]; xhr.url = arguments[1];
}, },
setRequestHeader: function(header, value) { setRequestHeader: function(header, value) {
xhr.requestHeaders[header] = value; xhr.requestHeaders[header] = value;
}, },
abort: function() { abort: function() {
}, },
readyState: 1, readyState: 1,
status: null, status: null,
send: function(data) { send: function(data) {
xhr.params = data; xhr.params = data;
}, },
getResponseHeader: function() {
}, getResponseHeader: function() {},
responseText: null, responseText: null,
response: function(response) { response: function(response) {
xhr.status = response.status; xhr.status = response.status;
xhr.responseText = response.responseText || ""; xhr.responseText = response.responseText || "";
xhr.readyState = 4; xhr.readyState = 4;
// jquery 1.3.x // uncomment for jquery 1.3.x support
// jasmine.Clock.tick(20); // jasmine.Clock.tick(20);
// jquery 1.4.x
xhr.onreadystatechange(); xhr.onreadystatechange();
} }
}; };
$.extend(xhr, options || {});
return xhr;
}
function mostRecentXhr() { jQuery.extend(xhr, options || {});
if (xhrs.length == 0) {
return null; return xhr;
} }
return xhrs[xhrs.length - 1];
}

View File

@ -151,4 +151,4 @@ c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetL
d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top- d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top-
f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset": f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset":
"pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in "pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in
e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window); e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);

View File

@ -36,6 +36,54 @@ Ajax.RealRequest = Class.create(Ajax.Request, {
} }
}); });
function stubXhr(options) {
var xhr = {
requestHeaders: {},
open: function() {
xhr.method = arguments[0];
xhr.url = arguments[1];
},
setRequestHeader: function(header, value) {
xhr.requestHeaders[header] = value;
},
abort: function() {
},
readyState: 1,
status: null,
send: function(data) {
xhr.params = data;
},
getResponseHeader: function() {},
responseText: null,
response: function(response) {
xhr.status = response.status;
xhr.responseText = response.responseText || "";
xhr.readyState = 4;
// uncomment for jquery 1.3.x support
// jasmine.Clock.tick(20);
xhr.onreadystatechange();
}
};
jQuery.extend(xhr, options || {});
return xhr;
}
// generic // generic
var ajaxRequests = []; var ajaxRequests = [];
@ -63,4 +111,7 @@ function mostRecentAjaxRequest() {
function clearAjaxRequests() { function clearAjaxRequests() {
ajaxRequests = []; ajaxRequests = [];
} }

View File

@ -1,6 +1,15 @@
jQuery.noConflict();
beforeEach(function() { beforeEach(function() {
clearAjaxRequests(); clearAjaxRequests();
spyOn(Ajax, "getTransport").andCallFake(function() {
return new FakeAjaxTransport(); spyOn(Ajax, "getTransport").andCallFake(function() {
}); return new FakeAjaxTransport();
});
spyOn(jQuery.ajaxSettings, 'xhr').andCallFake(function() {
var newXhr = stubXhr();
ajaxRequests.push(newXhr);
return newXhr;
});
}); });

View File

@ -0,0 +1,282 @@
describe("Jasmine Mock Ajax (for jQuery)", function() {
var request, anotherRequest, success, error, complete;
var sharedContext = {};
beforeEach(function() {
success = jasmine.createSpy("onSuccess");
error = jasmine.createSpy("onFailure");
complete = jasmine.createSpy("onComplete");
});
describe("when making a request", function () {
beforeEach(function() {
request = jQuery.ajax({
url: "example.com/someApi",
type: "GET",
success: success,
complete: complete,
error: error
});
});
it("should store URL and transport", function() {
expect(request.url).toEqual("example.com/someApi");
});
it("should queue the request", function() {
expect(ajaxRequests.length).toEqual(1);
});
it("should allow access to the queued request", function() {
expect(ajaxRequests[0]).toEqual(request);
});
describe("and then another request", function () {
beforeEach(function() {
anotherRequest = jQuery.ajax({
url: "example.com/someApi",
type: "GET",
success: success,
complete: complete,
error: error
});
});
it("should queue the next request", function() {
expect(ajaxRequests.length).toEqual(2);
});
it("should allow access to the other queued request", function() {
expect(ajaxRequests[1]).toEqual(anotherRequest);
});
});
describe("mostRecentAjaxRequest", function () {
describe("when there is one request queued", function () {
it("should return the request", function() {
expect(mostRecentAjaxRequest()).toEqual(request);
});
});
describe("when there is more than one request", function () {
beforeEach(function() {
anotherRequest = jQuery.ajax({
url: "example.com/someApi",
type: "GET",
success: success,
complete: complete,
error: error
});
});
it("should return the most recent request", function() {
expect(mostRecentAjaxRequest()).toEqual(anotherRequest);
});
});
describe("when there are no requests", function () {
beforeEach(function() {
clearAjaxRequests();
});
it("should return null", function() {
expect(mostRecentAjaxRequest()).toEqual(null);
});
});
});
describe("clearAjaxRequests()", function () {
beforeEach(function() {
clearAjaxRequests();
});
it("should remove all requests", function() {
expect(ajaxRequests.length).toEqual(0);
expect(mostRecentAjaxRequest()).toEqual(null);
});
});
});
xdescribe("when simulating a response with request.response", function () {
beforeEach(function() {
request = new Ajax.Request("idontcare", {
method: 'get',
onSuccess: success,
onFailure: error,
onComplete: complete
});
});
describe("and the response is Success", function () {
beforeEach(function() {
var response = {status: 200, contentType: "text/html", responseText: "OK!"};
request.response(response);
sharedContext.responseCallback = success;
sharedContext.status = response.status;
sharedContext.contentType = response.contentType;
sharedContext.responseText = response.responseText;
});
it("should call the success handler", function() {
expect(success).toHaveBeenCalled();
});
it("should not call the failure handler", function() {
expect(error).not.toHaveBeenCalled();
});
it("should call the complete handler", function() {
expect(complete).toHaveBeenCalled();
});
sharedAjaxResponseBehavior(sharedContext);
});
describe("and the response is Failure", function () {
beforeEach(function() {
var response = {status: 500, contentType: "text/html", responseText: "(._){"};
request.response(response);
sharedContext.responseCallback = error;
sharedContext.status = response.status;
sharedContext.contentType = response.contentType;
sharedContext.responseText = response.responseText;
});
it("should not call the success handler", function() {
expect(success).not.toHaveBeenCalled();
});
it("should call the failure handler", function() {
expect(error).toHaveBeenCalled();
});
it("should call the complete handler", function() {
expect(complete).toHaveBeenCalled();
});
sharedAjaxResponseBehavior(sharedContext);
});
describe("and the response is Success, but with JSON", function () {
var response;
beforeEach(function() {
var responseObject = {status: 200, contentType: "application/json", responseText: "{'foo':'bar'}"};
request.response(responseObject);
sharedContext.responseCallback = success;
sharedContext.status = responseObject.status;
sharedContext.contentType = responseObject.contentType;
sharedContext.responseText = responseObject.responseText;
response = success.mostRecentCall.args[0];
});
it("should call the success handler", function() {
expect(success).toHaveBeenCalled();
});
it("should not call the failure handler", function() {
expect(error).not.toHaveBeenCalled();
});
it("should call the complete handler", function() {
expect(complete).toHaveBeenCalled();
});
it("should return a JavaScript object", function() {
window.response = response;
expect(response.responseJSON).toEqual({foo: "bar"});
});
sharedAjaxResponseBehavior(sharedContext);
});
describe("the content type defaults to application/json", function () {
beforeEach(function() {
var response = {status: 200, responseText: "OK!"};
request.response(response);
sharedContext.responseCallback = success;
sharedContext.status = response.status;
sharedContext.contentType = "application/json";
sharedContext.responseText = response.responseText;
});
it("should call the success handler", function() {
expect(success).toHaveBeenCalled();
});
it("should not call the failure handler", function() {
expect(error).not.toHaveBeenCalled();
});
it("should call the complete handler", function() {
expect(complete).toHaveBeenCalled();
});
sharedAjaxResponseBehavior(sharedContext);
});
describe("and the response is null", function () {
beforeEach(function() {
request = jQuery.ajax({
url: "example.com/someApi",
type: "GET",
success: success,
complete: complete,
error: error
});
var response = {status: null, responseText: "whoops!"};
request.response(response);
sharedContext.responseCallback = on0;
sharedContext.status = 0;
sharedContext.contentType = 'application/json';
sharedContext.responseText = response.responseText;
});
it("should not call the success handler", function() {
expect(success).not.toHaveBeenCalled();
});
it("should not call the failure handler", function() {
expect(error).not.toHaveBeenCalled();
});
it("should call the on0 handler", function() {
expect(on0).toHaveBeenCalled();
});
it("should call the complete handler", function() {
expect(complete).toHaveBeenCalled();
});
sharedAjaxResponseBehavior(sharedContext);
});
});
});
function sharedAjaxResponseBehavior(context) {
describe("the response", function () {
var response;
beforeEach(function() {
response = context.responseCallback.mostRecentCall.args[0];
});
it("should have the expected status code", function() {
expect(response.status).toEqual(context.status);
});
it("should have the expected content type", function() {
expect(response.getHeader('Content-type')).toEqual(context.contentType);
});
it("should have the expected response text", function() {
expect(response.responseText).toEqual(context.responseText);
});
});
}

View File

@ -166,7 +166,6 @@ describe("Jasmine Mock Ajax (for Prototype.js)", function() {
sharedContext.responseText = responseObject.responseText; sharedContext.responseText = responseObject.responseText;
response = onSuccess.mostRecentCall.args[0]; response = onSuccess.mostRecentCall.args[0];
console.error(response)
}); });
it("should call the success handler", function() { it("should call the success handler", function() {