Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosrodriguez/1371407 to your computer and use it in GitHub Desktop.
Save carlosrodriguez/1371407 to your computer and use it in GitHub Desktop.
Simple jQuery (1.5+) AJAX Mocking (requires JSON, tested in jQuery 1.7))
/*!
* Simple jQuery (1.5+) AJAX Mocking - v0.1pre - 11/16/2011
* http://benalman.com/
*
* Copyright (c) 2011 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
(function($) {
function processRules(options) {
var transport;
$.each($.mockAjax.rules[options.dataType], function(k, rule) {
var matches = options.url.match(rule.re);
if (matches) {
transport = {
send: function(_, done) {
var response = rule.response;
if ($.isFunction(response)) {
response = response(matches, options);
}
done("200", "success", {status: JSON.stringify(response)});
},
abort: $.noop
};
return false;
}
});
return transport;
}
$.mockAjax = function(dataType, userRules) {
var rules = $.mockAjax.rules[dataType];
if (!rules) {
rules = $.mockAjax.rules[dataType] = {};
$.ajaxTransport(dataType, processRules);
}
$.each(userRules, function(pattern, response) {
rules[pattern] = {
re: new RegExp("^" + pattern + "$"),
response: response
};
});
};
$.mockAjax.rules = {};
}(jQuery));
// Simulate your API.
$.mockAjax("json", {
"/user": {status: -1},
"/user/(\\d+)": function(matches) {
return {status: 1, user: "sample user " + matches[1]};
}
});
// Unit tests.
test("user tests", function() {
expect(5);
stop();
$.getJSON("/user", function(data) {
ok(data, "data is returned from the server");
equal(data.status, "-1", "no user specified, status should be -1");
start();
});
stop();
$.getJSON("/user/123", function(data) {
ok(data, "data is returned from the server");
equal(data.status, "1", "user found, status should be 1");
equal(data.user, "sample user 123", "user found, status should be 1");
start();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment