问题描述
我在 Protractor 中发送 HTTP 获取请求时遇到问题.实际上,我需要在 UI 中执行一些操作后检查 DB 中的数据.
I am facing problem to send HTTP get request in Protractor. Actually, I need to check data in DB after perform some action in UI.
如果我能够使用 JQuery 来做这将非常有帮助,但我无法找到如何在 Protractor 中使用 JQuery.
It will be very helpful if I will be able to do it using JQuery, but I am not able to find a way how to use JQuery inside Protractor.
需要帮助!!
实际上,我们确实尝试使用如下所示的 Node.js 库,但遇到了问题.
Actually, we did try to use the Node.js lib as shown below, but facing problems in it.
var http = require('http');
var json_data;
http.get('SiteUrl', function(response) {
var bodyString = '';
response.setEncoding('utf8');
response.on("data", function(chunk) {
bodyString += chunk;
});
response.on('end', function() {
json_data = bodyString;
console.log("1---->" + json_data);
});
}).on('error', function(e) {
console.log("There is an error in GET request");
});
console.log("2---->" + json_data);
经过调试,我们发现问题是Protractor没有等待HTTP请求完成而只是传递.我们首先在控制台中获取 2---->
,然后是 1---->
.
After Debugging, we have found that the problem is Protractor is not waiting for HTTP request to be complete and just pass on. We are getting 2---->
first in console and then 1---->
.
推荐答案
我也使用 http 模块(用于不同的目的,用于重新初始化数据库).
I also use http module (for different purpose, for reinitialization of the database).
要让量角器等待结束请求,请使用承诺
To make protractor wait for ending the request, use promises
var http = require('http');
var json_data;
http.get('SiteUrl', function(response) {
var bodyString = '';
response.setEncoding('utf8');
response.on("data", function(chunk) {
bodyString += chunk;
});
response.on('end', function() {
json_data = bodyString;
console.log("1---->"+json_data);
// All the processing and Angular code should be here
console.log("2---->"+json_data);
});
}).on('error', function(e) {
console.log("There is an error in GET request");
});
如果你不喜欢把所有的数据处理都放到response.on('end')回调中,那就把回调单独做一个函数.
If you don't like putting all the data processing into response.on('end') callback, then make callback a separate function.
另外我不得不说,Protractor 并不是用来直接检查数据库的.它用于端到端测试.您最好构建一个复杂的场景,在其中一个页面上写入一些数据,然后转到另一个页面并期望数据被更新.
Additionally I have to say that Protractor is not intended to be used to check the database directly. It is for end-to-end testing. You should better build a complex scenario which writes some data on one of the page, go to another page and expects that data is updated.
这篇关于如何在 Protractor 中发出 HTTP GET+POST 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!