How to use protractor to get the response status c

2019-01-18 11:25发布

I'm using protractor for e2e testing.

I want to visit a url, say:

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

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?

标签: protractor
1条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-18 12:06

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.

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

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>
查看更多
登录 后发表回答