Skip to content
Extraits de code Groupes Projets
Valider 43f15642 rédigé par Florian Staudacher's avatar Florian Staudacher Validation de Jonne Haß
Parcourir les fichiers

update jasmine mock-ajax, port SpecHelper to jasmine 2.0

- some tests should be passing again now
parent 397606bc
Aucune branche associée trouvée
Aucune étiquette associée trouvée
Aucune requête de fusion associée trouvée
// Add custom matchers here, in a beforeEach block. Example: // for docs, see http://jasmine.github.io
//beforeEach(function() {
// this.addMatchers({
// toBePlaying: function(expectedSong) {
// var player = this.actual;
// return player.currentlyPlayingSong === expectedSong
// && player.isPlaying;
// }
// })
//});
beforeEach(function() { beforeEach(function() {
$('#jasmine_content').html(spec.readFixture("underscore_templates")); $('#jasmine_content').html(spec.readFixture("underscore_templates"));
jasmine.Clock.useMock();
jasmine.clock().install();
jasmine.Ajax.install();
Diaspora.Pages.TestPage = function() { Diaspora.Pages.TestPage = function() {
var self = this; var self = this;
...@@ -29,43 +21,56 @@ beforeEach(function() { ...@@ -29,43 +21,56 @@ beforeEach(function() {
Diaspora.page = new Page(); Diaspora.page = new Page();
Diaspora.page.publish("page/ready", [$(document.body)]); Diaspora.page.publish("page/ready", [$(document.body)]);
// matches flash messages with success/error and contained text
var flashMatcher = function(flash, id, text) {
textContained = true;
if( text ) {
textContained = (flash.text().indexOf(text) !== -1);
}
return flash.is(id) &&
flash.hasClass('expose') &&
textContained;
};
// add custom matchers for flash messages // add custom matchers for flash messages
this.addMatchers({ jasmine.addMatchers(customMatchers);
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() { afterEach(function() {
//spec.clearLiveEventBindings(); //spec.clearLiveEventBindings();
jasmine.clock().uninstall();
jasmine.Ajax.uninstall();
$("#jasmine_content").empty() $("#jasmine_content").empty()
expect(spec.loadFixtureCount).toBeLessThan(2); expect(spec.loadFixtureCount).toBeLessThan(2);
spec.loadFixtureCount = 0; spec.loadFixtureCount = 0;
}); });
// matches flash messages with success/error and contained text
var flashMatcher = function(flash, id, text) {
textContained = true;
if( text ) {
textContained = (flash.text().indexOf(text) !== -1);
}
return flash.is(id) &&
flash.hasClass('expose') &&
textContained;
};
var context = describe; var context = describe;
var spec = {}; 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){ window.stubView = function stubView(text){
var stubClass = Backbone.View.extend({ var stubClass = Backbone.View.extend({
...@@ -159,7 +164,7 @@ spec.retrieveFixture = function(fixtureName) { ...@@ -159,7 +164,7 @@ spec.retrieveFixture = function(fixtureName) {
// retrieve the fixture markup via xhr request to jasmine server // retrieve the fixture markup via xhr request to jasmine server
try { try {
xhr = new jasmine.XmlHttpRequest(); xhr = new XMLHttpRequest();
xhr.open("GET", path, false); xhr.open("GET", path, false);
xhr.send(null); xhr.send(null);
} catch(e) { } catch(e) {
......
/* /*
Jasmine-Ajax : a set of helpers for testing AJAX requests under the Jasmine
BDD framework for JavaScript.
Supports both Prototype.js and jQuery. Jasmine-Ajax : a set of helpers for testing AJAX requests under the Jasmine
BDD framework for JavaScript.
http://github.com/pivotal/jasmine-ajax http://github.com/pivotal/jasmine-ajax
Jasmine Home page: http://pivotal.github.com/jasmine 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 Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish, without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to permit persons to whom the Software is furnished to do so, subject to
the following conditions: the following conditions:
The above copyright notice and this permission notice shall be The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software. included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
// Jasmine-Ajax interface (function() {
var ajaxRequests = []; function extend(destination, source) {
for (var property in source) {
function mostRecentAjaxRequest() { destination[property] = source[property];
if (ajaxRequests.length > 0) { }
return ajaxRequests[ajaxRequests.length - 1]; return destination;
} else {
return null;
} }
}
function clearAjaxRequests() {
ajaxRequests = [];
}
// Fake XHR for mocking Ajax Requests & Responses
function FakeXMLHttpRequest() {
var extend = Object.extend || $.extend;
extend(this, {
requestHeaders: {},
open: function() {
this.method = arguments[0];
this.url = arguments[1];
this.readyState = 1;
},
setRequestHeader: function(header, value) {
this.requestHeaders[header] = value;
},
abort: function() { function MockAjax(global) {
this.readyState = 0; var requestTracker = new RequestTracker(),
}, stubTracker = new StubTracker(),
realAjaxFunction = global.XMLHttpRequest,
readyState: 0, 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();
}
};
onreadystatechange: function(isTimeout) { this.requests = requestTracker;
}, this.stubs = stubTracker;
}
status: null, function StubTracker() {
var stubs = [];
send: function(data) { this.addStub = function(stub) {
this.params = data; stubs.push(stub);
this.readyState = 2; };
},
getResponseHeader: function(name) { this.reset = function() {
return this.responseHeaders[name]; stubs = [];
}, };
getAllResponseHeaders: function() { this.findStub = function(url, data) {
var responseHeaders = []; for (var i = stubs.length - 1; i >= 0; i--) {
for (var i in this.responseHeaders) { var stub = stubs[i];
if (this.responseHeaders.hasOwnProperty(i)) { if (stub.matches(url, data)) {
responseHeaders.push(i + ': ' + this.responseHeaders[i]); return stub;
} }
} }
return responseHeaders.join('\r\n'); };
}, }
responseText: null, function fakeRequest(requestTracker, stubTracker) {
function FakeXMLHttpRequest() {
response: function(response) { requestTracker.track(this);
this.status = response.status; this.requestHeaders = {};
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.onreadystatechange();
},
responseTimeout: function() {
this.readyState = 4;
jasmine.Clock.tick(jQuery.ajaxSettings.timeout || 30000);
this.onreadystatechange('timeout');
} }
});
return this; 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) {
this.requestHeaders[header] = value;
},
abort: function() {
this.readyState = 0;
this.status = 0;
this.statusText = "abort";
this.onreadystatechange();
},
readyState: 0,
onload: function() {
},
onreadystatechange: function(isTimeout) {
},
status: null,
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) {
return this.responseHeaders[name];
},
getAllResponseHeaders: function() {
var responseHeaders = [];
for (var i in this.responseHeaders) {
if (this.responseHeaders.hasOwnProperty(i)) {
responseHeaders.push(i + ': ' + this.responseHeaders[i]);
}
}
return responseHeaders.join('\r\n');
},
responseText: null,
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" };
this.onload();
this.onreadystatechange();
},
responseTimeout: function() {
this.readyState = 4;
jasmine.clock().tick(30000);
this.onreadystatechange('timeout');
}
});
return FakeXMLHttpRequest;
}
jasmine.Ajax = { function RequestTracker() {
var requests = [];
this.track = function(request) {
requests.push(request);
};
this.first = function() {
return requests[0];
};
this.count = function() {
return requests.length;
};
this.reset = function() {
requests = [];
};
this.mostRecent = function() {
return requests[requests.length - 1];
};
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 {
if (requests[i].url == url_to_match) {
matching_requests.push(requests[i]);
}
}
}
isInstalled: function() { return matching_requests;
return jasmine.Ajax.installed == true; };
}, }
assertInstalled: function() { function RequestStub(url, stubData) {
if (!jasmine.Ajax.isInstalled()) { var split = url.split('?');
throw new Error("Mock ajax is not installed, use jasmine.Ajax.useMock()") this.url = split[0];
}
},
useMock: function() { var normalizeQuery = function(query) {
if (!jasmine.Ajax.isInstalled()) { return query ? query.split('&').sort().join('&') : undefined;
var spec = jasmine.getEnv().currentSpec; };
spec.after(jasmine.Ajax.uninstallMock);
jasmine.Ajax.installMock(); this.query = normalizeQuery(split[1]);
} this.data = normalizeQuery(stubData);
},
installMock: function() {
if (typeof jQuery != 'undefined') {
jasmine.Ajax.installJquery();
} else if (typeof Prototype != 'undefined') {
jasmine.Ajax.installPrototype();
} else {
throw new Error("jasmine.Ajax currently only supports jQuery and Prototype");
}
jasmine.Ajax.installed = true;
},
installJquery: function() { this.andReturn = function(options) {
jasmine.Ajax.mode = 'jQuery'; this.status = options.status || 200;
jasmine.Ajax.real = jQuery.ajaxSettings.xhr;
jQuery.ajaxSettings.xhr = jasmine.Ajax.jQueryMock;
}, this.contentType = options.contentType;
this.responseText = options.responseText;
};
installPrototype: function() { this.matches = function(fullUrl, data) {
jasmine.Ajax.mode = 'Prototype'; var urlSplit = fullUrl.split('?'),
jasmine.Ajax.real = Ajax.getTransport; url = urlSplit[0],
query = urlSplit[1];
return this.url === url && this.query === normalizeQuery(query) && (!this.data || this.data === normalizeQuery(data));
};
}
Ajax.getTransport = jasmine.Ajax.prototypeMock; if (typeof window === "undefined" && typeof exports === "object") {
}, exports.MockAjax = MockAjax;
jasmine.Ajax = new MockAjax(exports);
} else {
window.MockAjax = MockAjax;
jasmine.Ajax = new MockAjax(window);
}
}());
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);
};
}
\ No newline at end of file
0% Chargement en cours ou .
You are about to add 0 people to the discussion. Proceed with caution.
Terminez d'abord l'édition de ce message.
Veuillez vous inscrire ou vous pour commenter