14

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?

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • There is a wdio-intercept-service library but I noticed it doesn't work for me on Protractor. Is there a way to do it? – djangofan Apr 20 '21 at 21:57

1 Answers1

21

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>
Roger Keays
  • 3,117
  • 1
  • 31
  • 23
Leo Gallucci
  • 16,355
  • 12
  • 77
  • 110
  • Leo I think the link you have added to shows differently. Is this still the case? – Jimmy Kane Feb 21 '17 at 16:26
  • Sorry I don't have time to look into this old post, if there is a better more up-to-date answer please fill in and I'll up vote if it works :) :) – Leo Gallucci Feb 21 '17 at 18:55
  • 1
    it's OK. Indeed if I find a way I'll inform you and thanks for the answer. It's the one I'll try to follow as I only need some body checksums. Take care. – Jimmy Kane Feb 21 '17 at 22:11
  • @LeoGallucci Can you please help in https and post method with protractor. – Bhoomi Bhalani Nov 07 '17 at 06:19