Skip to content

Instantly share code, notes, and snippets.

@ChristiaanScheermeijer
Created May 18, 2015 14:59
Show Gist options
  • Save ChristiaanScheermeijer/6b024d5bf5b96c29460c to your computer and use it in GitHub Desktop.
Save ChristiaanScheermeijer/6b024d5bf5b96c29460c to your computer and use it in GitHub Desktop.
Simple Jasmine Ajax Mock
'use strict';
var routes = [];
/**
* Simple jQuery ajax mock for jasmine
*
* @example
*
* ## Create a mocked route
*
* ```js
* jasmine.ajaxMock()
* .when('GET', 'http://my-awesome.api/metadata.json', function() {
* // return response for success call
* return {
* id: 1
* };
* });
* ```
*
* ## Test
*
* ```js
* it('should get metadata with id 1', function() {
*
* $.get('http://my-awesome.api/metadata.json', function(response) {
* expect(response.id.toEqual(1));
* });
*
* });
* ```
*
*
* @param keepRoutes
* @returns {{when: when}}
*/
jasmine.ajaxMock = function (keepRoutes) {
// clear routes
if (true !== keepRoutes) {
routes = [];
}
if (!$._ajax) {
$._ajax = $.ajax;
$.ajax = function (url, settings) {
if (settings) {
settings.url = url;
} else {
settings = url;
}
for (var i = 0; i < routes.length; i++) {
if (routes[i].url === settings.url && routes[i].method.toLowerCase() === settings.type.toLowerCase()) {
var defer = jQuery.Deferred();
defer.resolveWith(routes[i].response());
if (settings.success) {
settings.success(routes[i].response());
}
return defer.promise();
}
}
return $._ajax(settings);
};
}
return {
when: function (method, url, response) {
routes.push({
method: method,
url: url,
response: response
});
return this;
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment