Gregion Gregion - 2 months ago 9
Node.js Question

The tale of Node.js and the https post request

Good [insert correct part of the day] Ladies and Gents!

In the past few week I was fiddling around with Node.js and Mocha. Happen to bump into a problem which is the following.

I try to test an https post request, but the result is never what I expect.
I can choose from either the test times out, or passes (when it should fail).

Could you please give me some hints/tips what could have gone wrong?



var chai = require('chai');
var https = require('https');

var options = {
hostname: "google.com",
method: "POST"
};


describe("Connection tests", function(){
it("should return 404", function(done){
https.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
chai.expect(res.statusCode).to.equal(404);
done(); //if done is here it times out.
});
//done - if done is here it returns success instead failure.
});
});




Answer

You need to call .end on the request to finish sending the request (otherwise, Node will wait for more data to be written to it first):

https.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  chai.expect(res.statusCode).to.equal(404);
  done();
}).end(); // <-- here