jasmine-ajax主要五個對象組成:ajax
function FakeXMLHttpRequest() {}
function RequestTracker() {}
RequestStub
):用做對僞造的AJAX請求作出響應。function RequestStub(url, stubData, method) {}
function StubTracker() {}
function ParamParser() {}
function arrayContains(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) { return true; } } return false; }
函數結構很明顯,斷定一個數組是否包含某一個值。json
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
其實結構很是明顯,使用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; }; }
經過jasmine.Ajax.stubs
便可訪問到StubTracker
對象,主動調用意義不大。reset
方法用於變量環境重置,addStub
方法在生成RequestStub
對象時調用。findStub
在xhr.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; } } }; }
請求攔截在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); }; }
主要負責值的解析。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(); }
代碼過長,分段說明。prototype
function FakeXMLHttpRequest() { requestTracker.track(this); this.requestHeaders = {}; this.overriddenMimeType = null; }
var iePropertiesThatCannotBeCopied = ['responseBody', 'responseText', 'responseXML', 'status', 'statusText', 'responseTimeout']; extend(FakeXMLHttpRequest.prototype, new window.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.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