如何使用量角器获取响应状态码和响应文本? [英] How to use protractor to get the response status code and response text?

查看:52
本文介绍了如何使用量角器获取响应状态码和响应文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 protractor 进行 e2e 测试.

I'm using protractor for e2e testing.

我想访问一个网址,例如:

I want to visit a url, say:

browser.get("http://my.test.com");

并获取 http 状态代码和所有响应正文,但我找不到获取它们的方法.有什么方法可以使用吗?

And get the http status code and all the response body text, but I can't find a way to get them. Is there any methods I can use?

推荐答案

获取 http 状态代码是不可能的,因为 已解决 selenium webdriver API 不会添加它 并且 Protractor 依赖 Selenium 与浏览器交互.

Getting the http status code it's not possible since it's been resolved that selenium webdriver API won't add it and Protractor depends on Selenium for interacting with the browser.

您需要为此找到解决方法,例如使用 NodeJS,因为 Protractor 在其中运行一个辅助函数,该函数可以理解 promise,因此 Protractor 在继续之前等待 http get:

You'll need to find a workaround for this, e.g. using NodeJS given that Protractor runs inside it with a helper function that understand promises so Protractor waits for the http get before continuing:

// A Protracterized httpGet() promise
function httpGet(siteUrl) {
    var http = require('http');
    var defer = protractor.promise.defer();

    http.get(siteUrl, function(response) {

        var bodyString = '';

        response.setEncoding('utf8');
        
        response.on("data", function(chunk) {
            bodyString += chunk;
        });
        
        response.on('end', function() {
            defer.fulfill({
                statusCode: response.statusCode,
                bodyString: bodyString
            });
        });

    }).on('error', function(e) {
        defer.reject("Got http.get error: " + e.message);
    });

    return defer.promise;
}

it('should return 200 and contain proper body', function() {
    httpGet("http://localhost:80").then(function(result) {
        expect(result.statusCode).toBe(200);
        expect(result.bodyString).toContain('Apache');
    });
});

其他选项可能会根据响应状态代码相应地更改 html 服务器端,如 这篇博文

Other option might be changing the html server side accordingly to the response status code as in this blog post

<h1 id="web_403">403 Access Denied</h1>

这篇关于如何使用量角器获取响应状态码和响应文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆