mock-ajax.js 20.5 KB
Newer Older
1 2
/*

3 4
Jasmine-Ajax - v3.2.0: a set of helpers for testing AJAX requests under the Jasmine
BDD framework for JavaScript.
5

6
http://github.com/jasmine/jasmine-ajax
7

8
Jasmine Home page: http://jasmine.github.io/
9

10
Copyright (c) 2008-2015 Pivotal Labs
11

12 13 14 15 16 17 18
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
19

20 21
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
22

23 24 25 26 27 28 29
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30

31
*/
32

33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
//Module wrapper to support both browser and CommonJS environment
(function (root, factory) {
    if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
        // CommonJS
        var jasmineRequire = require('jasmine-core');
        module.exports = factory(root, function() {
            return jasmineRequire;
        });
    } else {
        // Browser globals
        window.MockAjax = factory(root, getJasmineRequireObj);
    }
}(typeof window !== 'undefined' ? window : global, function (global, getJasmineRequireObj) {

// 
getJasmineRequireObj().ajax = function(jRequire) {
  var $ajax = {};

  $ajax.RequestStub = jRequire.AjaxRequestStub();
  $ajax.RequestTracker = jRequire.AjaxRequestTracker();
  $ajax.StubTracker = jRequire.AjaxStubTracker();
  $ajax.ParamParser = jRequire.AjaxParamParser();
  $ajax.event = jRequire.AjaxEvent();
  $ajax.eventBus = jRequire.AjaxEventBus($ajax.event);
  $ajax.fakeRequest = jRequire.AjaxFakeRequest($ajax.eventBus);
  $ajax.MockAjax = jRequire.MockAjax($ajax);

  return $ajax.MockAjax;
};
62

63 64 65
getJasmineRequireObj().AjaxEvent = function() {
  function now() {
    return new Date().getTime();
66 67
  }

68 69
  function noop() {
  }
70

71 72 73 74 75 76 77
  // Event object
  // https://dom.spec.whatwg.org/#concept-event
  function XMLHttpRequestEvent(xhr, type) {
    this.type = type;
    this.bubbles = false;
    this.cancelable = false;
    this.timeStamp = now();
78

79 80
    this.isTrusted = false;
    this.defaultPrevented = false;
81

82 83 84
    // Event phase should be "AT_TARGET"
    // https://dom.spec.whatwg.org/#dom-event-at_target
    this.eventPhase = 2;
85

86 87 88
    this.target = xhr;
    this.currentTarget = xhr;
  }
89

90 91 92
  XMLHttpRequestEvent.prototype.preventDefault = noop;
  XMLHttpRequestEvent.prototype.stopPropagation = noop;
  XMLHttpRequestEvent.prototype.stopImmediatePropagation = noop;
93

94 95
  function XMLHttpRequestProgressEvent() {
    XMLHttpRequestEvent.apply(this, arguments);
96

97 98 99 100
    this.lengthComputable = false;
    this.loaded = 0;
    this.total = 0;
  }
101

102 103
  // Extend prototype
  XMLHttpRequestProgressEvent.prototype = XMLHttpRequestEvent.prototype;
104

105 106 107
  return {
    event: function(xhr, type) {
      return new XMLHttpRequestEvent(xhr, type);
108 109
    },

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    progressEvent: function(xhr, type) {
      return new XMLHttpRequestProgressEvent(xhr, type);
    }
  };
};
getJasmineRequireObj().AjaxEventBus = function(eventFactory) {
  function EventBus(source) {
    this.eventList = {};
    this.source = source;
  }

  function ensureEvent(eventList, name) {
    eventList[name] = eventList[name] || [];
    return eventList[name];
  }
125

126 127 128 129 130 131 132 133
  function findIndex(list, thing) {
    if (list.indexOf) {
      return list.indexOf(thing);
    }

    for(var i = 0; i < list.length; i++) {
      if (thing === list[i]) {
        return i;
134
      }
135
    }
136

137 138
    return -1;
  }
139

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  EventBus.prototype.addEventListener = function(event, callback) {
    ensureEvent(this.eventList, event).push(callback);
  };

  EventBus.prototype.removeEventListener = function(event, callback) {
    var index = findIndex(this.eventList[event], callback);

    if (index >= 0) {
      this.eventList[event].splice(index, 1);
    }
  };

  EventBus.prototype.trigger = function(event) {
    var evt;

    // Event 'readystatechange' is should be a simple event.
    // Others are progress event.
    // https://xhr.spec.whatwg.org/#events
    if (event === 'readystatechange') {
      evt = eventFactory.event(this.source, event);
    } else {
      evt = eventFactory.progressEvent(this.source, event);
    }

    var eventListeners = this.eventList[event];

    if (eventListeners) {
      for (var i = 0; i < eventListeners.length; i++) {
        eventListeners[i].call(this.source, evt);
169
      }
170 171
    }
  };
172

173 174 175 176
  return function(source) {
    return new EventBus(source);
  };
};
177

178 179 180 181 182 183 184 185 186 187
getJasmineRequireObj().AjaxFakeRequest = function(eventBusFactory) {
  function extend(destination, source, propertiesToSkip) {
    propertiesToSkip = propertiesToSkip || [];
    for (var property in source) {
      if (!arrayContains(propertiesToSkip, property)) {
        destination[property] = source[property];
      }
    }
    return destination;
  }
188

189 190 191 192 193
  function arrayContains(arr, item) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] === item) {
        return true;
      }
194
    }
195 196
    return false;
  }
197

198 199 200 201 202 203 204
  function wrapProgressEvent(xhr, eventName) {
    return function() {
      if (xhr[eventName]) {
        xhr[eventName].apply(xhr, arguments);
      }
    };
  }
205

206 207 208 209 210 211 212 213 214 215
  function initializeEvents(xhr) {
    xhr.eventBus.addEventListener('readystatechange', wrapProgressEvent(xhr, 'onreadystatechange'));
    xhr.eventBus.addEventListener('loadstart', wrapProgressEvent(xhr, 'onloadstart'));
    xhr.eventBus.addEventListener('load', wrapProgressEvent(xhr, 'onload'));
    xhr.eventBus.addEventListener('loadend', wrapProgressEvent(xhr, 'onloadend'));
    xhr.eventBus.addEventListener('progress', wrapProgressEvent(xhr, 'onprogress'));
    xhr.eventBus.addEventListener('error', wrapProgressEvent(xhr, 'onerror'));
    xhr.eventBus.addEventListener('abort', wrapProgressEvent(xhr, 'onabort'));
    xhr.eventBus.addEventListener('timeout', wrapProgressEvent(xhr, 'ontimeout'));
  }
216

217 218 219 220 221 222 223 224 225
  function unconvertibleResponseTypeMessage(type) {
    var msg = [
      "Can't build XHR.response for XHR.responseType of '",
      type,
      "'.",
      "XHR.response must be explicitly stubbed"
    ];
    return msg.join(' ');
  }
226

227 228 229 230 231 232 233 234
  function fakeRequest(global, requestTracker, stubTracker, paramParser) {
    function FakeXMLHttpRequest() {
      requestTracker.track(this);
      this.eventBus = eventBusFactory(this);
      initializeEvents(this);
      this.requestHeaders = {};
      this.overriddenMimeType = null;
    }
235

236 237 238 239 240 241 242
    function findHeader(name, headers) {
      name = name.toLowerCase();
      for (var header in headers) {
        if (header.toLowerCase() === name) {
          return headers[header];
        }
      }
243 244
    }

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    function normalizeHeaders(rawHeaders, contentType) {
      var headers = [];

      if (rawHeaders) {
        if (rawHeaders instanceof Array) {
          headers = rawHeaders;
        } else {
          for (var headerName in rawHeaders) {
            if (rawHeaders.hasOwnProperty(headerName)) {
              headers.push({ name: headerName, value: rawHeaders[headerName] });
            }
          }
        }
      } else {
        headers.push({ name: "Content-Type", value: contentType || "application/json" });
      }

      return headers;
    }
264

265 266 267 268 269 270 271 272 273
    function parseXml(xmlText, contentType) {
      if (global.DOMParser) {
        return (new global.DOMParser()).parseFromString(xmlText, 'text/xml');
      } else {
        var xml = new global.ActiveXObject("Microsoft.XMLDOM");
        xml.async = "false";
        xml.loadXML(xmlText);
        return xml;
      }
274 275
    }

276 277 278 279 280 281 282 283 284
    var xmlParsables = ['text/xml', 'application/xml'];

    function getResponseXml(responseText, contentType) {
      if (arrayContains(xmlParsables, contentType.toLowerCase())) {
        return parseXml(responseText, contentType);
      } else if (contentType.match(/\+xml$/)) {
        return parseXml(responseText, 'text/xml');
      }
      return null;
285 286
    }

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
    var iePropertiesThatCannotBeCopied = ['responseBody', 'responseText', 'responseXML', 'status', 'statusText', 'responseTimeout', 'responseURL'];
    extend(FakeXMLHttpRequest.prototype, new global.XMLHttpRequest(), iePropertiesThatCannotBeCopied);
    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.requestHeaders = {};
        this.eventBus.trigger('readystatechange');
      },

      setRequestHeader: function(header, value) {
        if(this.requestHeaders.hasOwnProperty(header)) {
          this.requestHeaders[header] = [this.requestHeaders[header], value].join(', ');
        } else {
          this.requestHeaders[header] = value;
        }
      },

      overrideMimeType: function(mime) {
        this.overriddenMimeType = mime;
      },

      abort: function() {
        this.readyState = 0;
        this.status = 0;
        this.statusText = "abort";
        this.eventBus.trigger('readystatechange');
        this.eventBus.trigger('progress');
        this.eventBus.trigger('abort');
        this.eventBus.trigger('loadend');
      },

      readyState: 0,

      onloadstart: null,
      onprogress: null,
      onabort: null,
      onerror: null,
      onload: null,
      ontimeout: null,
      onloadend: null,
      onreadystatechange: null,

      addEventListener: function() {
        this.eventBus.addEventListener.apply(this.eventBus, arguments);
      },

      removeEventListener: function(event, callback) {
        this.eventBus.removeEventListener.apply(this.eventBus, arguments);
      },

      status: null,

      send: function(data) {
        this.params = data;
        this.eventBus.trigger('loadstart');

        var stub = stubTracker.findStub(this.url, data, this.method);
        if (stub) {
          if (stub.isReturn()) {
            this.respondWith(stub);
          } else if (stub.isError()) {
            this.responseError();
          } else if (stub.isTimeout()) {
            this.responseTimeout();
          }
        }
      },

      contentType: function() {
        return findHeader('content-type', this.requestHeaders);
      },

      data: function() {
        if (!this.params) {
          return {};
        }

        return paramParser.findParser(this).parse(this.params);
      },

      getResponseHeader: function(name) {
        name = name.toLowerCase();
        var resultHeader;
        for(var i = 0; i < this.responseHeaders.length; i++) {
          var header = this.responseHeaders[i];
          if (name === header.name.toLowerCase()) {
            if (resultHeader) {
              resultHeader = [resultHeader, header.value].join(', ');
            } else {
              resultHeader = header.value;
            }
          }
        }
        return resultHeader;
      },

      getAllResponseHeaders: function() {
        var responseHeaders = [];
        for (var i = 0; i < this.responseHeaders.length; i++) {
          responseHeaders.push(this.responseHeaders[i].name + ': ' +
            this.responseHeaders[i].value);
        }
        return responseHeaders.join('\r\n') + '\r\n';
      },

      responseText: null,
      response: null,
      responseType: null,
      responseURL: null,

      responseValue: function() {
        switch(this.responseType) {
          case null:
          case "":
          case "text":
            return this.readyState >= 3 ? this.responseText : "";
          case "json":
            return JSON.parse(this.responseText);
          case "arraybuffer":
            throw unconvertibleResponseTypeMessage('arraybuffer');
          case "blob":
            throw unconvertibleResponseTypeMessage('blob');
          case "document":
            return this.responseXML;
        }
      },
417 418


419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
      respondWith: function(response) {
        if (this.readyState === 4) {
          throw new Error("FakeXMLHttpRequest already completed");
        }

        this.status = response.status;
        this.statusText = response.statusText || "";
        this.responseHeaders = normalizeHeaders(response.responseHeaders, response.contentType);
        this.readyState = 2;
        this.eventBus.trigger('readystatechange');

        this.responseText = response.responseText || "";
        this.responseType = response.responseType || "";
        this.responseURL = response.responseURL || null;
        this.readyState = 4;
        this.responseXML = getResponseXml(response.responseText, this.getResponseHeader('content-type') || '');
        if (this.responseXML) {
          this.responseType = 'document';
        }

        if ('response' in response) {
          this.response = response.response;
        } else {
          this.response = this.responseValue();
        }

        this.eventBus.trigger('readystatechange');
        this.eventBus.trigger('progress');
        this.eventBus.trigger('load');
        this.eventBus.trigger('loadend');
      },

      responseTimeout: function() {
        if (this.readyState === 4) {
          throw new Error("FakeXMLHttpRequest already completed");
        }
        this.readyState = 4;
        jasmine.clock().tick(30000);
        this.eventBus.trigger('readystatechange');
        this.eventBus.trigger('progress');
        this.eventBus.trigger('timeout');
        this.eventBus.trigger('loadend');
      },

      responseError: function() {
        if (this.readyState === 4) {
          throw new Error("FakeXMLHttpRequest already completed");
        }
        this.readyState = 4;
        this.eventBus.trigger('readystatechange');
        this.eventBus.trigger('progress');
        this.eventBus.trigger('error');
        this.eventBus.trigger('loadend');
      }
    });

    return FakeXMLHttpRequest;
  }

  return fakeRequest;
};

getJasmineRequireObj().MockAjax = function($ajax) {
  function MockAjax(global) {
    var requestTracker = new $ajax.RequestTracker(),
      stubTracker = new $ajax.StubTracker(),
      paramParser = new $ajax.ParamParser(),
      realAjaxFunction = global.XMLHttpRequest,
      mockAjaxFunction = $ajax.fakeRequest(global, requestTracker, stubTracker, paramParser);

    this.install = function() {
      if (global.XMLHttpRequest === mockAjaxFunction) {
        throw "MockAjax is already installed.";
      }

      global.XMLHttpRequest = mockAjaxFunction;
    };

    this.uninstall = function() {
      if (global.XMLHttpRequest !== mockAjaxFunction) {
        throw "MockAjax not installed.";
      }
      global.XMLHttpRequest = realAjaxFunction;

      this.stubs.reset();
      this.requests.reset();
      paramParser.reset();
    };

    this.stubRequest = function(url, data, method) {
      var stub = new $ajax.RequestStub(url, data, method);
      stubTracker.addStub(stub);
      return stub;
    };

    this.withMock = function(closure) {
      this.install();
      try {
        closure();
      } finally {
        this.uninstall();
      }
    };

    this.addCustomParamParser = function(parser) {
      paramParser.add(parser);
    };

    this.requests = requestTracker;
    this.stubs = stubTracker;
  }

  return MockAjax;
};

getJasmineRequireObj().AjaxParamParser = function() {
  function ParamParser() {
    var defaults = [
      {
        test: function(xhr) {
          return (/^application\/json/).test(xhr.contentType());
        },
        parse: function jsonParser(paramString) {
          return JSON.parse(paramString);
        }
      },
      {
        test: function(xhr) {
          return true;
        },
        parse: function naiveParser(paramString) {
          var data = {};
          var params = paramString.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]));
          }
          return data;
        }
      }
    ];
    var paramParsers = [];

    this.add = function(parser) {
      paramParsers.unshift(parser);
    };

    this.findParser = function(xhr) {
        for(var i in paramParsers) {
          var parser = paramParsers[i];
          if (parser.test(xhr)) {
            return parser;
          }
        }
    };

    this.reset = function() {
      paramParsers = [];
      for(var i in defaults) {
        paramParsers.push(defaults[i]);
      }
    };

    this.reset();
  }

  return ParamParser;
};

getJasmineRequireObj().AjaxRequestStub = function() {
  var RETURN = 0,
      ERROR = 1,
      TIMEOUT = 2;

  function RequestStub(url, stubData, method) {
    var normalizeQuery = function(query) {
      return query ? query.split('&').sort().join('&') : undefined;
    };

    if (url instanceof RegExp) {
      this.url = url;
      this.query = undefined;
    } else {
      var split = url.split('?');
      this.url = split[0];
      this.query = split.length > 1 ? normalizeQuery(split[1]) : undefined;
608
    }
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

    this.data = (stubData instanceof RegExp) ? stubData : normalizeQuery(stubData);
    this.method = method;

    this.andReturn = function(options) {
      this.action = RETURN;
      this.status = options.status || 200;

      this.contentType = options.contentType;
      this.response = options.response;
      this.responseText = options.responseText;
      this.responseHeaders = options.responseHeaders;
      this.responseURL = options.responseURL;
    };

    this.isReturn = function() {
      return this.action === RETURN;
    };

    this.andError = function() {
      this.action = ERROR;
    };

    this.isError = function() {
      return this.action === ERROR;
    };

    this.andTimeout = function() {
      this.action = TIMEOUT;
    };

    this.isTimeout = function() {
      return this.action === TIMEOUT;
    };

    this.matches = function(fullUrl, data, method) {
      var urlMatches = false;
      fullUrl = fullUrl.toString();
      if (this.url instanceof RegExp) {
        urlMatches = this.url.test(fullUrl);
      } else {
        var urlSplit = fullUrl.split('?'),
            url = urlSplit[0],
            query = urlSplit[1];
        urlMatches = this.url === url && this.query === normalizeQuery(query);
      }
      var dataMatches = false;
      if (this.data instanceof RegExp) {
        dataMatches = this.data.test(data);
      } else {
        dataMatches = !this.data || this.data === normalizeQuery(data);
      }
      return urlMatches && dataMatches && (!this.method || this.method === method);
    };
  }

  return RequestStub;
};

getJasmineRequireObj().AjaxRequestTracker = function() {
  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) {
      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]);
          }
        }
      }

      return matching_requests;
    };
  }

  return RequestTracker;
};

getJasmineRequireObj().AjaxStubTracker = function() {
  function StubTracker() {
    var stubs = [];

    this.addStub = function(stub) {
      stubs.push(stub);
    };

    this.reset = function() {
      stubs = [];
    };

    this.findStub = function(url, data, method) {
      for (var i = stubs.length - 1; i >= 0; i--) {
        var stub = stubs[i];
        if (stub.matches(url, data, method)) {
          return stub;
        }
      }
    };
  }

  return StubTracker;
744
};
745 746 747 748 749 750 751 752


    var jRequire = getJasmineRequireObj();
    var MockAjax = jRequire.ajax(jRequire);
    jasmine.Ajax = new MockAjax(global);

    return MockAjax;
}));