Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use protractor to get the response status code and response text?

Tags:

protractor

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?

like image 292
Freewind Avatar asked Aug 05 '14 11:08

Freewind


1 Answers

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>
like image 82
Leo Gallucci Avatar answered Oct 25 '22 17:10

Leo Gallucci