QUnit Mocked AJAX

by Joshua McNeese

HTML

<script src="http://code.jquery.com/qunit/qunit-1.12.0.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.12.0.css">
<h1 id="qunit-header">Test Suite</h1>

 <h2 id="qunit-banner"></h2>

<div id="qunit-testrunner-toolbar"></div>
 <h2 id="qunit-userAgent"></h2>

<ol id="qunit-tests"></ol>
<div id="qunit-fixture">
    <ul class="nav">' + '
        <li class="nav-item first">1</li>' + '
        <li class="nav-item ">2</li>' + '
        <li class="nav-item ">3</li>' + '
        <li class="nav-item last">4</li>' +</ul>
</div>

JavaScript

/*!
 * Simple jQuery (1.5+) AJAX Mocking - v0.1.1 - 2012-08-17
 * http://benalman.com/
 *
 * Copyright (c) 2012 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($) {

  // Process all rules for a given AJAX request.
  function processRules(options) {
    // The dataType (eg. "json").
    var dataType = options.dataType || '*';
    // If a rule is matched, override the built-in transport.
    var transport;
    // Iterate over all specified rules for this dataType, defaulting to
    // catch-all "*" rules if there are no dataType-specific rules.
    var rules = $.mockAjax.rules[dataType] || $.mockAjax.rules['*'] || [];
    $.each(rules, function(_, rule) {
      // Test the AJAX request URL against this rule's regexp.
      var matches = options.url.match(rule.re);
      // If there was a match, override the default transport.
      if (matches) {
        transport = {
          // Override the transport's send to immediately return a result.
          send: function(_, done) {
            // Get the response value.
            var response = rule.response;
            // If the response is a function, invoke it, passing in the matches
            // array and the AJAX request options, and get its result.
            if ($.isFunction(response)) {
              response = response(matches, options);
            }
            // If the dataType is "json" or "jsonp" and not a string, serialize
            // it into a valid JSON string. Note: requires JSON!
            if (/^json/.test(dataType) && typeof response !== "string") {
              response = window.JSON ? JSON.stringify(response) : String(response);
            }
            // Respond successfully!
            var delay = $.mockAjax.options.delay;
            setTimeout(function() {
              done("200", "success", {status: response});
            }, $.isFunction(delay) ? delay() : delay);
          },
          // Don't do...