[英]Testing post in bare Node.js app with Mocha and Superagent
希望這一天過得愉快。
因此,我試圖在Node中構建一些TDD印章,為此,我構建了一個超級裸機應用程序,該應用程序運行簡單的GET和POST請求。 它所做的只是服務於世界上最簡單的表單,然后將用戶輸入的內容輸入此表單並將其顯示在屏幕上。 這是原始節點,不涉及任何框架。 我正在使用Mocha和Superagent進行測試,並且卡在POST測試中。 這是我的應用程序:
var http = require('http');
var qs = require('querystring');
var server = http.createServer(function(req, res){
switch(req.method){
case 'GET':
console.log("Calling get");
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end("<p>Hello World!</p>" +
"<form method='post' action='/'>" +
"<input type='text' name='field'>" +
"<input type='submit'>" +
"</form>");
break;
case 'POST':
var body = "";
req.on('data', function(data){
body += data;
})
req.on('end', function(){
var post = qs.parse(body);
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end("<p>" + post.field + "</p>")
// console.log(req)
console.log(post);
});
}
})
server.listen(8080);
console.log('Server running on port 8080.')
這是我的測試:
var request = require('superagent');
var expect = require('expect.js');
describe('Main page', function(){
it("should get 'Hello World!'", function(done){
request.get('localhost:8080').end(function(res){
expect(res).to.exist;
expect(res.status).to.equal(200);
expect(res.text).to.contain("World");
done();
});
});
it("should display input text from a form.", function(done){
request.post('localhost:8080')
.send({field: "Test string."})
.end(function(res){
expect(res).to.exist;
expect(res.status).to.equal(200);
expect(res.text).to.contain("Test");
done();
})
});
});
我喜歡在學習事物時使其盡可能簡單,這樣我就可以隔離正在做的事情。 據我對Superagent的了解,.send()方法應該使用一個包含各種后置鍵和值的對象,然后將其傳遞給應用程序並沿着給定的路線運行。 但是,當我運行測試時,除了Expect(res.text).to.contain(“ Test”)斷言之外,其他所有內容都通過了。 我收到了摩卡咖啡預期的錯誤
未定義
以包含“測試”。 當我剛啟動應用程序並在瀏覽器中運行時,一切都很好。我已經為此努力了一段時間,現在我要去研究蜂巢。 正如我提到的,我是TDD新手,但我想成為一名考驗的神,這真的使我的頭腦變得更加殘酷。 任何啟發將不勝感激。
並由我自己獲得。 當您注視足夠長的時間時,它們將教您什么文檔。
查看位於此處的文檔后:
http://visionmedia.github.io/superagent/#post-/%20put%20requests
我意識到,要讓Superagent正確發布,我必須在發送信息之前告訴它發布的類型,如下所示:
it("should display input text from a form.", function(done){
request.post('localhost:8080')
.type('form')
.send({field: "Test string."})
.end(function(res){
expect(res).to.exist;
expect(res.status).to.equal(200);
expect(res.text).to.contain("Test");
done();
})
});
漂亮的東西。 希望其他人對此有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.