简体   繁体   English

如何在Node.js测试中关闭net.Server?

[英]How to close a net.Server in Node.js tests?

The example works find, but when I replace server.listen(1234); 该示例可以找到,但是当我替换server.listen(1234); with server.listen(1234, '127.0.0.1'); server.listen(1234, '127.0.0.1'); the test return the following error: "Error: Not running" 测试返回以下错误:“错误:未运行”

describe('Server', function() {
  it('should do something', function(done) {
    var server = new net.Server();
    server.listen(1234);

    // do something

    server.close();
    done();
  });
});

Can you explain to mw why? 你能向大众解释为什么吗?

That is because listen is asynchronous. 那是因为listen是异步的。 It just happens that in the case where no second parameter is given, it opens synchronously enough that close doesn't fail. 碰巧的是,在没有给定第二个参数的情况下,它同步打开的程度足以确保close不会失败。 For that matter, close is also async. 因此, close也是异步的。

it('should do something', function(done) {
  var server = new net.Server();
  server.listen(1234, '127.0.0.1', function(){
    // do something

    server.close(done);
  });
});

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

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