2016-09-22 110 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就足夠了,但是,嘿,寶貝步驟!