简体   繁体   English

在node.js中使用誓言时出现奇怪的错误

[英]Strange error when I use vows in node.js

I'm trying to start my node.js project with BDD using vows. 我正在尝试使用誓言使用BDD启动我的node.js项目。 Then I got this strange error. 然后我得到了这个奇怪的错误。

I was trying to write a small route testing for express with vows and here is my original code, 我试图用誓言为Express编写小型路由测试,这是我的原始代码,

node_server.prototype.mainpage = function(callback) {
  http.get({host:'localhost', port:this.port, path:'/', agent:false}, function(res){
  callback(res.statusCode);
  });
}

And here is how I write my vows testing 这是我写誓言测试的方式

vows.describe('Request to the server').addBatch({
'Should get http 200': {
      topic: function () {
        app_server.mainpage(this.callback)
      },

      'we get 200': function (statusCode) {
        app_server.close_server();
        assert.equal(statusCode, 200);
      }
  },
}).run(); // Run it

Vows always report an unexpected error even though the statusCode is correct, like this 即使statusCode正确,誓言也会始终报告意外错误,就像这样

» An unexpected error was caught: 200

So I change my mainpage function like this 所以我这样改变我的主页功能

node_server.prototype.mainpage = function(callback) {
  http.get({host:'localhost', port:this.port, path:'/', agent:false}, function(res){
      callback("error", res.statusCode); // Here I added a err message in front of the status code.
  });
}

And I also change my test suite as 我也将测试套件更改为

'we get 200': function (err, statusCode) {

Then this testing worked! 然后这个测试成功了! I'm just wondering how could this strange situation happened. 我只是想知道这种奇怪的情况怎么发生。 I've read the documentation of vows but I didn't find anywhere they said I must put 2 parameters to a cb instead of 1. 我已经阅读了誓言的文档,但是我什么都没发现他们说我必须将2个参数而不是1放到cb中。

Give me some clues! 给我一些线索! Thank you in advance! 先感谢您!

The Vows documentation doesn't mention it, but it's assuming the error first callback pattern, which is widely adopted by the Node.js community. Vows文档没有提及它,但是它假定了错误优先回调模式,该模式已被Node.js社区广泛采用。 In this pattern, the first parameter of the callback is always an error. 在这种模式下,回调的第一个参数始终是错误。 If it's null or undefined, then you know the async operation succeeded. 如果它为null或未定义,则说明异步操作成功。 I would recommend using this pattern for all of your own code as well, even if the function won't ever produce an error parameter. 即使该函数永远不会产生错误参数,我也建议对您自己的所有代码也使用此模式。

If you use this pattern yourself, you can more easily make use of other libraries like async , which can make things a lot easier for complicated apps. 如果您自己使用此模式,则可以更轻松地利用其他库(例如async) ,这对于复杂的应用程序来说可以使事情变得容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM