2016-09-22 108 views
0

在过去的几个星期里,我在摆弄Node.js和Mocha。碰巧遇到以下问题。Node.js和https发布请求的故事

我尝试测试一个https发布请求,但结果不是我所期望的。 我可以选择测试超时,或通过(当它应该失败)。

您能否给我一些提示/提示可能出错?

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

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

 

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

回答

1

你需要调用.end的要求完成发送请求(否则,节点将等待更多的数据首先被写入到它):

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

[敲打键盘上的头加剧]谢谢指出我的白痴! – Gregion

1

下面是一个替代的解决问题的方法:

HTTPS而不是我使用请求

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

 
describe("Connection tests", function(){ 
 
\t it("is the request approach", function(done){ 
 
\t \t request({ 
 
\t \t \t url: "https://www.google.com", 
 
\t \t \t method: "POST", 
 
\t \t \t json: true 
 
\t \t }, function(error, response, body){ 
 
\t \t \t console.log(response.statusCode); 
 
\t \t \t chai.expect(response.statusCode).to.equal(405); 
 
\t \t \t done(); 
 
\t \t }); 
 
\t }); 
 
});

我知道我实际上没有发布任何内容,但简单的GET就足够了,但是,嘿,宝贝步骤!