问题
I'm using Protracotr for e2e testing.
I want to test response from HTTP in protractor. Basically:
- I have running some NodeJS server.
- I want to send request to this server
- Receive some JSON data
- Parse those data
- 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