Forked from cowboy/jquery.ba-simple-ajax-mocking.js
Created
November 16, 2011 21:08
-
-
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))
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* 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)); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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