当 setInterval(...) 运行 时,Mocha 测试套件永远不会结束
Mocha test suite never ends when setInterval(...) running
我有一套测试,其中包含带有 setInterval(...)
调用的代码。
当 运行通过 windows powershell 命令行在 mocha 中运行此代码时,所有测试都将 运行,但测试 运行ner 之后将无限期挂起。
我使用的命令是mocha "./unitTests/**/*.js"
有没有办法强制 运行ner 关闭测试?
或者有没有办法确定代码在测试环境中 运行ning 以便我可以禁用我的 setInterval(...)
调用?
示例代码:
// MODULE TO TEST
setInterval(function(){
// do cleanup task
}, 1000000);
function testFunction(){
return "val";
}
export {
testFunction
}
// TEST MODULE
describe("Test setInterval", function() {
it("should finish", function() {
testFunction().should.be.equal("val");
// This test will complete and all others, but the entire suite will not
});
});
您可以使用 done() 结束测试,就像这个例子:
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done){
var user = new User('Luna');
user.save(function(err) {
if (err) done(err);
else done();
});
});
});
});
根本原因是 Mocha 默认 认为 suite 是 "done" 而 Node 认为进程是 "done"。并且 默认情况下 节点在调用进程 "done" 之前等待所有未清除的超时和间隔为 "done"。 ("uncleared" 超时或间隔是已经创建但从未被 clearTimeout/clearInterval
调用过的超时或间隔。)
当您传递给 setTimeout
的回调已完成执行时完成超时,但永远不会完成间隔,因为根据设计它会永远调用其回调。
您的选择是:
判断区间清除的条件,用clearInterval
清除。
对 setInterval
的 return 值使用 unref
。这告诉 Node 在决定进程是否为 "done".
时忽略间隔
使用 --exit
选项调用 mocha
(在 Mocha 4 中引入),当 Mocha 完成测试套件时强制退出进程。
我会使用选项 1 或 2。第三个选项有效,但如果您的测试套件变得更加复杂,它可能会隐藏您应该注意的问题。如果有更专注的解决方案可以使用,我不会使用它。
我有一套测试,其中包含带有 setInterval(...)
调用的代码。
当 运行通过 windows powershell 命令行在 mocha 中运行此代码时,所有测试都将 运行,但测试 运行ner 之后将无限期挂起。
我使用的命令是mocha "./unitTests/**/*.js"
有没有办法强制 运行ner 关闭测试?
或者有没有办法确定代码在测试环境中 运行ning 以便我可以禁用我的 setInterval(...)
调用?
示例代码:
// MODULE TO TEST
setInterval(function(){
// do cleanup task
}, 1000000);
function testFunction(){
return "val";
}
export {
testFunction
}
// TEST MODULE
describe("Test setInterval", function() {
it("should finish", function() {
testFunction().should.be.equal("val");
// This test will complete and all others, but the entire suite will not
});
});
您可以使用 done() 结束测试,就像这个例子:
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done){
var user = new User('Luna');
user.save(function(err) {
if (err) done(err);
else done();
});
});
});
});
根本原因是 Mocha 默认 认为 suite 是 "done" 而 Node 认为进程是 "done"。并且 默认情况下 节点在调用进程 "done" 之前等待所有未清除的超时和间隔为 "done"。 ("uncleared" 超时或间隔是已经创建但从未被 clearTimeout/clearInterval
调用过的超时或间隔。)
当您传递给 setTimeout
的回调已完成执行时完成超时,但永远不会完成间隔,因为根据设计它会永远调用其回调。
您的选择是:
判断区间清除的条件,用
clearInterval
清除。对
setInterval
的 return 值使用unref
。这告诉 Node 在决定进程是否为 "done". 时忽略间隔
使用
--exit
选项调用mocha
(在 Mocha 4 中引入),当 Mocha 完成测试套件时强制退出进程。
我会使用选项 1 或 2。第三个选项有效,但如果您的测试套件变得更加复杂,它可能会隐藏您应该注意的问题。如果有更专注的解决方案可以使用,我不会使用它。