我希望这一天能找到你。
所以我试图在 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() 方法应该采用一个包含各种 post 键和值的对象,然后将其传递给应用程序并沿着给定的路线运行。但是当我运行测试时,除了 expect(res.text).to.contain("Test") 断言之外,一切都通过了。我收到 Mocha 预期的错误
不明确的
'以包含'测试'。当我刚刚启动应用程序并在浏览器中运行它时,一切都很好。我已经为此苦苦挣扎了一段时间,现在我要去蜂巢思维了。正如我所提到的,我是一名 TDD 新手,但我想成为一名测试之神,这真的让我的醇厚变得刺耳。任何启示将不胜感激。