json - Protractor :HTTP 响应测试

标签 json node.js protractor httprequest httpresponse

我正在使用 Protracotr用于端到端测试。

我想在 Protractor 中测试来自 HTTP 的响应。 基本上:

  1. 我已经运行了一些 NodeJS 服务器。
  2. 我想向这个服务器发送请求
  3. 接收一些JSON数据
  4. 解析这些数据
  5. 检查是否正确

我正在使用“http”NODEJS Lib 进行 http 调用 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');
            }
        });
    });
});

我可以在 console.log 中看到很好解析的响应消息,但我无法测试任何东西,我的测试结果是:

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

console log在测试结束后记录下来,没有断言。

请帮忙,如何在 Protractor 中测试来自服务器的那些响应(JSON 格式)?

最佳答案

对于异步测试,您需要将完成的回调传递给您的函数。然后在成功时调用 done() 或在失败时调用 done.fail()。参见 Jasmine's Asynchronous support文档。

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

关于json - Protractor :HTTP 响应测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41467777/

相关文章:

json - 如何在 flutter 中反序列化来自json的对象列表

json - 覆盖 Play JSON Combinator Writes 的值

java - 我如何查看从 GSON JsonReader 收到了多少字节

node.js - 使用 Loopback 滑动访问 token 的到期时间

javascript - 为什么我没有成功地在第二个代码部分中获得嵌入的 "if"来完成其工作?

javascript - 如何在键值对的特定位置写入js文件?

python - 如何从 json 流中解析对象

javascript - 我可以从服务器向客户端 GRPC 发送自定义错误消息吗?

angularjs - Protractor 从 dom 中移除元素

angularjs - 将元素名称/ID 用于使用 Protractor 测试 AngularJS 的元素