>我有一个节点.js + Express Web服务器,我正在用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>AppDataRoamingnpmnode_modulesmochlibrunnable.js:165:14)
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15)
如果我跳过 5 个测试中的任何一个,它就会成功通过。如果我重新排序测试,也会出现同样的问题(它总是最后一个超时)。将测试分成几组也不会改变事情。
从戳它开始,最终测试的请求被发送到 Web 服务器(使用 http 模块),但它没有被快递接收。有些测试发出一个请求,有些则提出多个请求。它不会影响我跳过哪些结果。我无法在摩卡之外复制这种行为。
这到底是怎么回事?
对于 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 完全关闭它,但我还没有尝试过)。