节点单元:测试功能中的运行时/抛出错误是_silent_ [英] Nodeunit: Runtime/thrown errors in test function are _silent_
问题描述
使用NodeUnit的要点之一是编写新功能并经常对其进行测试.问题是,如果其中一个经过测试的函数抛出错误(包括JS运行时错误),则该错误不会显示给用户. 这是最简单的测试用例:(请注意a.b.c.d会导致运行时错误)
One of the points of using NodeUnit is to write new functions and test them often. Problem is, if one of the tested functions throws an error (including JS runtime errors), the error is not shown to the user. Here is the simplest possible test case: (Note that a.b.c.d will cause a runtime error)
exports.all = {
one: function( test ){
test.done();
},
two: function( test ){
as( function( err, res ){
test.done();
});
},
}
function as( callback ){
process.nextTick( function() {
a = testMe();
callback( null, a );
});
}
function testMe(){
a.b.c.d.e = 100;
return 10;
}
但是,testMe()可能是我正在开发的新功能.未初始化的变量或任何内容都将保持沉默.
However, testMe() might be a new function I am developing. An uninitialised variable, or anything, will just fall silent.
推荐答案
通过uncaughtException
事件将自己未捕获的异常处理添加到测试文件中:
Add your own uncaught exception handling to your test file either via the uncaughtException
event:
process.on('uncaughtException', function(err) {
console.error(err.stack);
});
或者通过创建域并向其中添加process
(或测试使用的任何事件发射器),以便您可以捕获在使用process.nextTick
时发生的错误:
Or by creating a domain and adding process
to it (or whatever event emitter(s) your tests use) so that you can catch the errors that occur within your use of process.nextTick
:
var dom = require('domain').create();
dom.add(process);
dom.on('error', function(err) {
console.error(err.stack);
});
无论哪种方式,您都将获得类似于以下内容的控制台输出:
Either way, you'll then get console output that looks like:
ReferenceError: a is not defined
at testMe (/home/test/test.js:24:3)
at /home/test/test.js:18:9
at process._tickDomainCallback (node.js:459:13)
这篇关于节点单元:测试功能中的运行时/抛出错误是_silent_的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!