我正在使用 Protracotr用于端到端测试。
我想在 Protractor 中测试来自 HTTP 的响应。 基本上:
- 我已经运行了一些 NodeJS 服务器。
- 我想向这个服务器发送请求
- 接收一些JSON数据
- 解析这些数据
- 检查是否正确
我正在使用“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/