update jasmine mock-ajax, port SpecHelper to jasmine 2.0

- some tests should be passing again now
This commit is contained in:
Florian Staudacher 2014-03-01 01:57:02 +01:00 committed by Jonne Haß
parent 397606bc44
commit 43f156420d
2 changed files with 279 additions and 198 deletions

View file

@ -1,18 +1,10 @@
// Add custom matchers here, in a beforeEach block. Example:
//beforeEach(function() {
// this.addMatchers({
// toBePlaying: function(expectedSong) {
// var player = this.actual;
// return player.currentlyPlayingSong === expectedSong
// && player.isPlaying;
// }
// })
//});
// for docs, see http://jasmine.github.io
beforeEach(function() {
$('#jasmine_content').html(spec.readFixture("underscore_templates"));
jasmine.Clock.useMock();
jasmine.clock().install();
jasmine.Ajax.install();
Diaspora.Pages.TestPage = function() {
var self = this;
@ -29,6 +21,21 @@ beforeEach(function() {
Diaspora.page = new Page();
Diaspora.page.publish("page/ready", [$(document.body)]);
// add custom matchers for flash messages
jasmine.addMatchers(customMatchers);
});
afterEach(function() {
//spec.clearLiveEventBindings();
jasmine.clock().uninstall();
jasmine.Ajax.uninstall();
$("#jasmine_content").empty()
expect(spec.loadFixtureCount).toBeLessThan(2);
spec.loadFixtureCount = 0;
});
// matches flash messages with success/error and contained text
var flashMatcher = function(flash, id, text) {
@ -42,30 +49,28 @@ beforeEach(function() {
textContained;
};
// add custom matchers for flash messages
this.addMatchers({
toBeSuccessFlashMessage: function(containedText) {
var flash = this.actual;
return flashMatcher(flash, '#flash_notice', containedText);
},
toBeErrorFlashMessage: function(containedText) {
var flash = this.actual;
return flashMatcher(flash, '#flash_error', containedText);
}
});
});
afterEach(function() {
//spec.clearLiveEventBindings();
$("#jasmine_content").empty()
expect(spec.loadFixtureCount).toBeLessThan(2);
spec.loadFixtureCount = 0;
});
var context = describe;
var spec = {};
var customMatchers = {
toBeSuccessFlashMessage: function(util) {
return {
compare: function(actual, expected) {
var result = {};
result.pass = flashMatcher(actual, '#flash_notice', expected);
return result;
}
};
},
toBeErrorFlashMessage: function(util) {
return {
compare: function(actual, expected) {
var result = {};
result.pass = flashMatcher(actual, '#flash_error', expected);
return result;
}
};
}
};
window.stubView = function stubView(text){
var stubClass = Backbone.View.extend({
@ -159,7 +164,7 @@ spec.retrieveFixture = function(fixtureName) {
// retrieve the fixture markup via xhr request to jasmine server
try {
xhr = new jasmine.XmlHttpRequest();
xhr = new XMLHttpRequest();
xhr.open("GET", path, false);
xhr.send(null);
} catch(e) {

View file

@ -1,14 +1,13 @@
/*
Jasmine-Ajax : a set of helpers for testing AJAX requests under the Jasmine
BDD framework for JavaScript.
Supports both Prototype.js and jQuery.
http://github.com/pivotal/jasmine-ajax
Jasmine Home page: http://pivotal.github.com/jasmine
Copyright (c) 2008-2010 Pivotal Labs
Copyright (c) 2008-2013 Pivotal Labs
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@ -31,31 +30,86 @@
*/
// Jasmine-Ajax interface
var ajaxRequests = [];
function mostRecentAjaxRequest() {
if (ajaxRequests.length > 0) {
return ajaxRequests[ajaxRequests.length - 1];
} else {
return null;
(function() {
function extend(destination, source) {
for (var property in source) {
destination[property] = source[property];
}
return destination;
}
function clearAjaxRequests() {
ajaxRequests = [];
function MockAjax(global) {
var requestTracker = new RequestTracker(),
stubTracker = new StubTracker(),
realAjaxFunction = global.XMLHttpRequest,
mockAjaxFunction = fakeRequest(requestTracker, stubTracker);
this.install = function() {
global.XMLHttpRequest = mockAjaxFunction;
};
this.uninstall = function() {
global.XMLHttpRequest = realAjaxFunction;
this.stubs.reset();
this.requests.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();
}
};
this.requests = requestTracker;
this.stubs = stubTracker;
}
// Fake XHR for mocking Ajax Requests & Responses
function StubTracker() {
var stubs = [];
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 fakeRequest(requestTracker, stubTracker) {
function FakeXMLHttpRequest() {
var extend = Object.extend || $.extend;
extend(this, {
requestHeaders: {},
requestTracker.track(this);
this.requestHeaders = {};
}
extend(FakeXMLHttpRequest.prototype, window.XMLHttpRequest);
extend(FakeXMLHttpRequest.prototype, {
open: function() {
this.method = arguments[0];
this.url = arguments[1];
this.username = arguments[3];
this.password = arguments[4];
this.readyState = 1;
this.onreadystatechange();
},
setRequestHeader: function(header, value) {
@ -64,10 +118,16 @@ function FakeXMLHttpRequest() {
abort: function() {
this.readyState = 0;
this.status = 0;
this.statusText = "abort";
this.onreadystatechange();
},
readyState: 0,
onload: function() {
},
onreadystatechange: function(isTimeout) {
},
@ -76,6 +136,27 @@ function FakeXMLHttpRequest() {
send: function(data) {
this.params = data;
this.readyState = 2;
this.onreadystatechange();
var stub = stubTracker.findStub(this.url, data);
if (stub) {
this.response(stub);
}
},
data: function() {
var data = {};
if (typeof this.params !== 'string') { return data; }
var params = this.params.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]));
data[key].sort();
}
return data;
},
getResponseHeader: function(name) {
@ -96,112 +177,107 @@ function FakeXMLHttpRequest() {
response: function(response) {
this.status = response.status;
this.statusText = response.statusText || "";
this.responseText = response.responseText || "";
this.readyState = 4;
this.responseHeaders = response.responseHeaders ||
{"Content-type": response.contentType || "application/json" };
// uncomment for jquery 1.3.x support
// jasmine.Clock.tick(20);
this.onload();
this.onreadystatechange();
},
responseTimeout: function() {
this.readyState = 4;
jasmine.Clock.tick(jQuery.ajaxSettings.timeout || 30000);
jasmine.clock().tick(30000);
this.onreadystatechange('timeout');
}
});
return this;
return FakeXMLHttpRequest;
}
function RequestTracker() {
var requests = [];
jasmine.Ajax = {
this.track = function(request) {
requests.push(request);
};
isInstalled: function() {
return jasmine.Ajax.installed == true;
},
this.first = function() {
return requests[0];
};
assertInstalled: function() {
if (!jasmine.Ajax.isInstalled()) {
throw new Error("Mock ajax is not installed, use jasmine.Ajax.useMock()")
}
},
this.count = function() {
return requests.length;
};
useMock: function() {
if (!jasmine.Ajax.isInstalled()) {
var spec = jasmine.getEnv().currentSpec;
spec.after(jasmine.Ajax.uninstallMock);
this.reset = function() {
requests = [];
};
jasmine.Ajax.installMock();
}
},
this.mostRecent = function() {
return requests[requests.length - 1];
};
installMock: function() {
if (typeof jQuery != 'undefined') {
jasmine.Ajax.installJquery();
} else if (typeof Prototype != 'undefined') {
jasmine.Ajax.installPrototype();
this.at = function(index) {
return requests[index];
};
this.filter = function(url_to_match) {
if (requests.length == 0) return [];
var matching_requests = [];
for (var i = 0; i < requests.length; i++) {
if (url_to_match instanceof RegExp &&
url_to_match.test(requests[i].url)) {
matching_requests.push(requests[i]);
} else if (url_to_match instanceof Function &&
url_to_match(requests[i])) {
matching_requests.push(requests[i]);
} else {
throw new Error("jasmine.Ajax currently only supports jQuery and Prototype");
if (requests[i].url == url_to_match) {
matching_requests.push(requests[i]);
}
jasmine.Ajax.installed = true;
},
installJquery: function() {
jasmine.Ajax.mode = 'jQuery';
jasmine.Ajax.real = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = jasmine.Ajax.jQueryMock;
},
installPrototype: function() {
jasmine.Ajax.mode = 'Prototype';
jasmine.Ajax.real = Ajax.getTransport;
Ajax.getTransport = jasmine.Ajax.prototypeMock;
},
uninstallMock: function() {
jasmine.Ajax.assertInstalled();
if (jasmine.Ajax.mode == 'jQuery') {
jQuery.ajaxSettings.xhr = jasmine.Ajax.real;
} else if (jasmine.Ajax.mode == 'Prototype') {
Ajax.getTransport = jasmine.Ajax.real;
}
jasmine.Ajax.reset();
},
reset: function() {
jasmine.Ajax.installed = false;
jasmine.Ajax.mode = null;
jasmine.Ajax.real = null;
},
jQueryMock: function() {
var newXhr = new FakeXMLHttpRequest();
ajaxRequests.push(newXhr);
return newXhr;
},
prototypeMock: function() {
return new FakeXMLHttpRequest();
},
installed: false,
mode: null
}
// Jasmine-Ajax Glue code for Prototype.js
if (typeof Prototype != 'undefined' && Ajax && Ajax.Request) {
Ajax.Request.prototype.originalRequest = Ajax.Request.prototype.request;
Ajax.Request.prototype.request = function(url) {
this.originalRequest(url);
ajaxRequests.push(this);
};
Ajax.Request.prototype.response = function(responseOptions) {
return this.transport.response(responseOptions);
return matching_requests;
};
}
function RequestStub(url, stubData) {
var split = url.split('?');
this.url = split[0];
var normalizeQuery = function(query) {
return query ? query.split('&').sort().join('&') : undefined;
};
this.query = normalizeQuery(split[1]);
this.data = normalizeQuery(stubData);
this.andReturn = function(options) {
this.status = options.status || 200;
this.contentType = options.contentType;
this.responseText = options.responseText;
};
this.matches = function(fullUrl, data) {
var urlSplit = fullUrl.split('?'),
url = urlSplit[0],
query = urlSplit[1];
return this.url === url && this.query === normalizeQuery(query) && (!this.data || this.data === normalizeQuery(data));
};
}
if (typeof window === "undefined" && typeof exports === "object") {
exports.MockAjax = MockAjax;
jasmine.Ajax = new MockAjax(exports);
} else {
window.MockAjax = MockAjax;
jasmine.Ajax = new MockAjax(window);
}
}());