【问题标题】:Mocha tests timeout if more than 4 tests are run at once如果一次运行超过 4 个测试,则 Mocha 测试超时
【发布时间】:2013-10-21 13:50:07
【问题描述】:

我有一个 node.js + express 网络服务器,我正在用 Mocha 进行测试。我在测试工具中启动 Web 服务器,并连接到 mongodb 以查找输出:

describe("Api", function() {        
    before(function(done) {
        // start server using function exported from another js file
        // connect to mongo db
    });

    after(function(done) {
        // shut down server
        // close mongo connection
    });

    beforeEach(function(done) {
        // empty mongo collection
    });

    describe("Events", function() {    
        it("Test1", ...);
        it("Test2", ...);
        it("Test3", ...);
        it("Test4", ...);
        it("Test5", ...);
    });
});

如果 Mocha 一次运行超过 4 个测试,则会超时:

4 passing (2s)
1 failing

1) Api Test5:
   Error: timeout of 2000ms exceeded
    at null.<anonymous> (C:\Users\<username>\AppData\Roaming\npm\node_modules\moch\lib\runnable.js:165:14)
    at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)

如果我跳过 任何 5 个测试之一,它会成功通过。如果我重新排序测试(它总是最后一个超时),也会出现同样的问题。将测试分组也不会改变任何事情。

通过查看,最终测试的请求正在发送到 Web 服务器(使用 http 模块),但没有被 express 接收。有些测试提出一个请求,有些则不止一个。它不影响我跳过的结果。我无法在 mocha 之外复制这种行为。

到底发生了什么?

【问题讨论】:

  • 我假设你总是打电话给done?另外,您的测试是否有机会使用http
  • 我总是打电话给done(或者至少,将它传递给回调)。我正在使用http 向网络服务器发出请求。

标签: node.js mongodb express mocha.js


【解决方案1】:

对于 Mocha,如果您为(测试)函数的回调(通常称为 done)声明第一个参数,您必须调用它,否则 Mocha 将等到它被调用(最终超时)。如果您在测试中不需要它,请不要声明它:

it('test1', function(done) {
  ..
  // 'done' declared, so call it (eventually, usually when some async action is done)
  done();
});

it('test2', function() {
  // not an async test, not declaring 'done', obviously no need to call it
});

既然您使用的是http,请尝试增加http.globalAgent.maxSockets(默认为5):

var http = require('http');
http.globalAgent.maxSockets = 100;

(我相信 0 会完全关闭它,但我没有尝试过)。

【讨论】:

  • 原来是 http 的连接池导致了这个问题。我已禁用代理,所有测试现在都可以正常工作。作为记录,在maxSockets 上设置0 不起作用,但在请求选项中禁用代理则可以。
  • 我也遇到了这个。更多相关信息在stackoverflow.com/questions/15533448/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
  • 1970-01-01
  • 1970-01-01
  • 2017-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多