Protractor: HTTP Response Testing

社会主义新天地 提交于 2020-01-01 16:42:09

问题


I'm using Protracotr for e2e testing.

I want to test response from HTTP in protractor. Basically:

  1. I have running some NodeJS server.
  2. I want to send request to this server
  3. Receive some JSON data
  4. Parse those data
  5. Check if they are correct

I'm using "http" NODEJS Lib to make http calls GET+POST.

var http = require('http');

describe("Some test", function() {

    function httpGet(siteUrl) {
        http.get(siteUrl, function(response) {

            response.setEncoding('utf8');
            response.on("data", function(chunk) {
                bodyString += chunk;
            });

            response.on('end', function() {
                defer.fulfill({
                    bodyString: bodyString
                });
            });

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

        return defer.promise;
    }

    it('Test case', function(){
        httpGet("http://localhost:3333/path/1/10").then(function(result) {
            var json_data = JSON.parse(result.bodyString);

            for (var i = 0; i < json_data.length; ++i) {
                console.log("label: " + json_data[i].label);
                expect(json_data[i].label).toEqual('abc');
            }
        });
    });
});

I can see response message nice parsed in console.log, but I'm not able to test anything, my test results are:

Finished in 0.019 seconds
1 test, 0 assertions, 0 failures

label: Text1
label: Text2

[launcher] 0 instance(s) of WebDriver still running
[launcher] chrome #1 passed

Process finished with exit code 0

The console log is write down after finish of test and no assertion has been done.

Any help please, how to test those responses (in JSON format) from server in Protractor?


回答1:


For async tests, you'll need to pass the done callback to your function. Then call done() on success or done.fail() on failure. See Jasmine's Asynchronous support documentation.

it('Test case', function(done){
    httpGet("http://localhost:3333/path/1/10").then((result) => {
        var json_data = JSON.parse(result.bodyString);

        for (var i = 0; i < json_data.length; ++i) {
            console.log("label: " + json_data[i].label);
        }
        done();
    }).catch(err => {
        done.fail();
    });
});


来源:https://stackoverflow.com/questions/41467777/protractor-http-response-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!