通过将此脚本注入到浏览器中,可以拦截应用程序中的所有xhr调用。并存储响应一些全局变量,我保存在Windows变量。
(function(XHR) {
"use strict";
var open = XHR.prototype.open;
var send = XHR.prototype.send;
XHR.prototype.open = function(method, url, async, user, pass) {
this._url = url;
open.call(this, method, url, async, user, pass);
};
XHR.prototype.send = function(data) {
var self = this;
var oldOnReadyStateChange;
var url = this._url;
function onReadyStateChange() {
if(self.readyState == 4 /* complete */) {
/* This is where you can put code that you want to execute post-complete*/
/* URL is kept in this._url */
if(self._url=='api/v1/groups')
{
var request=JSON.parse(data);
if(request.method=='createGroup') {
var XHRInterceptObj=new Object();
XHRInterceptObj.request=request;
XHRInterceptObj.response=self;
window._groupCreation =XHRInterceptObj;
}
else if(request.method=='getGroupDetails') {
var XHRInterceptObj=new Object();
XHRInterceptObj.request=request;
XHRInterceptObj.response=self;
window._groupDetails =XHRInterceptObj;
}
}
}
if(oldOnReadyStateChange) {
oldOnReadyStateChange();
}
}
/* Set xhr.noIntercept to true to disable the interceptor for a particular call */
if(!this.noIntercept) {
if(this.addEventListener) {
this.addEventListener("readystatechange", onReadyStateChange, false);
} else {
oldOnReadyStateChange = this.onreadystatechange;
this.onreadystatechange = onReadyStateChange;
}
}
//console.log('data',data);
send.call(this, data);
}
})(XMLHttpRequest);
你可以从这个全局变量中获得响应数据。
browser.executeScript('return window._groupCreation;').then(function(obj){
console.log(obj.responseText);
});
在这个脚本中,我们实际上是使用原型和拦截调用为XHR对象添加了附加功能。
[在量角器测试中修改http响应]的可能的重复(http://stackoverflow.com/questions/26506331/modify-an-http-response-in-a-protractor-test) – 2014-12-19 18:35:44
这将有助于你发布了一个代码示例。你在用茉莉花吗?如果是这样,你看看jasmine2中新的'done()'回调吗? – finspin 2015-07-25 08:32:47