jasmine-ajax源碼解析


整體概述

jasmine-ajax主要五個對象組成:ajax

  • 請求僞造對象(FackXMLHttpRequest):
function FakeXMLHttpRequest() {}
  • 請求跟蹤對象(RequestTracker):
function RequestTracker() {}
  • 請求攔截對象(RequestStub):用做對僞造的AJAX請求作出響應。
function RequestStub(url, stubData, method) {}
  • 請求攔截跟蹤對象(StubTracker):
function StubTracker() {}
  • 參數解析(ParamParser):
function ParamParser() {}

輔助函數

arrayContains

function arrayContains(arr, item) {
for (var i = 0; i < arr.length; i++) {
  if (arr[i] === item) {
    return true;
  }
}
return false;
}

函數結構很明顯,斷定一個數組是否包含某一個值。json

extend

function extend(destination, source, propertiesToSkip) {
    propertiesToSkip = propertiesToSkip || [];
    for (var property in source) {
      if (!arrayContains(propertiesToSkip, property)) {
        destination[property] = source[property];
      }
    }
    return destination;
  }

此函數實現對象擴展,propertiesToSkip參數爲source中需排除掉的鍵,餘下的鍵值對覆蓋寫入destination數組

初始化語句

if (typeof window === "undefined" && typeof exports === "object") {
    exports.MockAjax = MockAjax;
    jasmine.Ajax = new MockAjax(exports);
  } else {
    window.MockAjax = MockAjax;
    jasmine.Ajax = new MockAjax(window);
  }

首先斷定是否commonjs環境,不是則傳遞window變量。在describe內部,便可訪問經過jasmine.Ajax使用MockAjax對象。app

RequestTracker

其實結構很是明顯,使用jasmine.Ajax.requests便可訪問到RequestTracker對象,而後經過first, mostRecent, at, filter 等方法獲取仿造的request對象,多用於對HTTP請求對象進行斷定,如方法,路徑,數據,headers等等,須要重點關注。reset, track手動調用意義不大,前者用於重置變量環境,後者在生成僞造XHR時調用。ide

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) {
      if (requests.length === 0) { return []; }
      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;
    };
  }

StubTracker

經過jasmine.Ajax.stubs便可訪問到StubTracker對象,主動調用意義不大。reset方法用於變量環境重置,addStub方法在生成RequestStub對象時調用。findStubxhr.open()調用時,斷定是否認義過response函數

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;
        }
      }
    };
  }

RequestStub

請求攔截在url, stubData, method同時匹配的狀況下才會啓動攔截。this

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;
    }

    this.data = normalizeQuery(stubData);
    this.method = method;

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

      this.contentType = options.contentType;
      this.responseText = options.responseText;
    };

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

ParamParser

主要負責值的解析。paramParsers參數爲parser對象數組。findParser遍歷paramParsers,經過test屬性斷定是否啓用對應的parse方法處理數據。若決定調用,則遍歷結束,返回該對象。add方法通常會經過jasmine.Ajax.addCustomParamParser(parser)調用,優先級上,後添加的>先添加的>默認的。url

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();
  }

FackXMLHttpRequest

代碼過長,分段說明。prototype

  • FakeXMLHttpRequest
    實例化後,即添加進入requestTracker,便於後期訪問。
function FakeXMLHttpRequest() {
  requestTracker.track(this);
  this.requestHeaders = {};
  this.overriddenMimeType = null;
}
  • 原型繼承
    此處感受比較好玩,是繼承真的XMLHttpRequest對象,只是去掉幾個特殊鍵值對,後面會進行處理。
var iePropertiesThatCannotBeCopied = ['responseBody', 'responseText', 'responseXML', 'status', 'statusText', 'responseTimeout'];
    extend(FakeXMLHttpRequest.prototype, new window.XMLHttpRequest(), iePropertiesThatCannotBeCopied);
  • Request僞造
    熟悉原生ajax的應該很容易看懂。重點在於,send方法調用時,會當即在stubs裏尋找匹配當前url,method,data的響應攔截器,若是預約義過了,則會馬上傳遞給response函數進行響應,不然須要以後手動調用response函數進行響應。
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.onreadystatechange();
      },

      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.onreadystatechange();
      },

      readyState: 0,

      onload: function() {
      },

      onreadystatechange: function(isTimeout) {
      },

      status: null,

      send: function(data) {
        this.params = data;
        this.readyState = 2;
        this.onreadystatechange();

        var stub = stubTracker.findStub(this.url, data, this.method);
        if (stub) {
          this.response(stub);
        }
      },

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

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

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

      getResponseHeader: function(name) {
        return findHeader(name, this.responseHeaders);
      },

      getAllResponseHeaders: function() {
        var responseHeaders = [];
        for (var i in this.responseHeaders) {
          if (this.responseHeaders.hasOwnProperty(i)) {
            responseHeaders.push(i + ': ' + this.responseHeaders[i]);
          }
        }
        return responseHeaders.join('\r\n');
      },

      responseText: null,

      response: function(response) {
        if (this.readyState === 4) {
          throw new Error("FakeXMLHttpRequest already completed");
        }
        this.status = response.status;
        this.statusText = response.statusText || "";
        this.responseText = response.responseText || "";
        this.readyState = 4;
        this.responseHeaders = response.responseHeaders ||
          {"Content-Type": response.contentType || "application/json" };

        this.onload();
        this.onreadystatechange();
      },

      responseTimeout: function() {
        if (this.readyState === 4) {
          throw new Error("FakeXMLHttpRequest already completed");
        }
        this.readyState = 4;
        jasmine.clock().tick(30000);
        this.onreadystatechange('timeout');
      }
    });

    return FakeXMLHttpRequest;
  }

經驗交流

QQ: 491229492
Email: huang.jian@eisoo.comcode

相關文章
相關標籤/搜索