希望您这一天过得愉快。
所以我试图在 Node 中构建一些 TDD,为此我构建了一个 super 简单的应用程序,它运行一个简单的 GET 和 POST 请求。它所做的就是提供世界上最简单的表单,然后将用户输入到该表单中的内容并将其显示在屏幕上。这是原始 Node,不涉及任何框架。我正在使用 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") 断言之外,一切都通过了。我收到一条错误消息,Mocha 期望“
undefined
”包含“Test”。当我刚刚启动应用程序并在浏览器中运行它时,一切都很好。我已经为此苦苦挣扎了一段时间,现在我要转向 hive 思维了。正如我提到的,我是一个 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();
})
});
漂亮的东西。希望其他人觉得这有帮助。
关于javascript - 使用 Mocha 和 Superagent 在裸 Node.js 应用程序中测试帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25715078/