【问题标题】:Protractor testing angular $http interceptors量角器测试角度 $http 拦截器
【发布时间】:2014-10-25 10:06:44
【问题描述】:

我正在尝试进行角度量角器测试,该测试在提交时会发送一个常规的 ajax 请求,然后在响应腿上截获该请求。 $http 拦截器打开一个自定义对话框,等待用户输入(用户/密码)以进行进一步的身份验证。

问题是量角器坐在那里等待 HTTP 响应完成但从未完成,因为它已被拦截并且只是超时。我找不到让量角器 sendKeys 到这些对话框的方法,因为它仍在等待 HTTP 请求完成(它永远不会因为它被拦截)。

那么本质上,量角器框架是否可以处理 $http 截获的响应并在需要时提供额外的浏览器输入?或者有什么解决办法?

谢谢!!

【问题讨论】:

标签: angularjs http protractor


【解决方案1】:

您可以通过将此脚本注入浏览器来拦截应用程序中的所有 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 对象添加附加功能。

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多