来自本机代码的 mocha 测试中未处理的拒绝
Unhandled rejections in mocha tests from native code
我在 mocha 测试中收到 "unhandled rejection" 消息,但我不知道问题的确切根源是什么,因为这是异步发生的。
我知道我可以为全局 unhandledRejection 事件添加一个事件侦听器,例如:
process.on('unhandledRejection', function(reason) {
console.error(reason);
process.exit(1);
});
但这并没有什么帮助,因为跟踪如下:
{ Error: ENOENT: no such file or directory, open '/tmp/testfile.json'
at Error (native)
cause:
{ Error: ENOENT: no such file or directory, open '/tmp/testfile.json'
at Error (native)
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/tmp/testfile.json' },
isOperational: true,
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/tmp/testfile.json' }
问题与节点的内置处理程序相同。没有回溯。
显然我没有得到正确的回溯,因为拒绝发生在本机 fs 模块中。
如果我尝试 运行 只是测试此跟踪发生的位置,它根本不会发生。这可能是因为在某处 "earlier" 设置了一个 运行away 承诺。指定的 /tmp/ 路径在测试代码或实际实现代码中的任何地方都不存在。 testfile.json 确实存在,但不在该路径中。
我是 运行宁摩卡 3.5.3 节点 6.5.0。
那么接下来的问题是:如何缩小范围找到有问题的代码?
一种通用方法。将问题一分为二:
- 将一些测试套件文件移动到一个单独的目录,这样它们就不会在测试期间执行
- 重新运行 mocha
- 观察失败消息是否仍然存在
- 如果是,继续移动更多文件。如果不是,有问题的文件是最后移动的文件之一。
然后继续平分引起问题的特定文件。注释掉代码,直到不执行有问题的代码。
我不确定它是否有帮助,但您也可以从 unhandledRejection
侦听器获取 Promise
作为参数,以获得更有用的输出。文档 here
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason);
// application specific logging, throwing an error, or other logic here
});
我在 mocha 测试中收到 "unhandled rejection" 消息,但我不知道问题的确切根源是什么,因为这是异步发生的。
我知道我可以为全局 unhandledRejection 事件添加一个事件侦听器,例如:
process.on('unhandledRejection', function(reason) {
console.error(reason);
process.exit(1);
});
但这并没有什么帮助,因为跟踪如下:
{ Error: ENOENT: no such file or directory, open '/tmp/testfile.json'
at Error (native)
cause:
{ Error: ENOENT: no such file or directory, open '/tmp/testfile.json'
at Error (native)
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/tmp/testfile.json' },
isOperational: true,
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: '/tmp/testfile.json' }
问题与节点的内置处理程序相同。没有回溯。
显然我没有得到正确的回溯,因为拒绝发生在本机 fs 模块中。 如果我尝试 运行 只是测试此跟踪发生的位置,它根本不会发生。这可能是因为在某处 "earlier" 设置了一个 运行away 承诺。指定的 /tmp/ 路径在测试代码或实际实现代码中的任何地方都不存在。 testfile.json 确实存在,但不在该路径中。
我是 运行宁摩卡 3.5.3 节点 6.5.0。
那么接下来的问题是:如何缩小范围找到有问题的代码?
一种通用方法。将问题一分为二:
- 将一些测试套件文件移动到一个单独的目录,这样它们就不会在测试期间执行
- 重新运行 mocha
- 观察失败消息是否仍然存在
- 如果是,继续移动更多文件。如果不是,有问题的文件是最后移动的文件之一。
然后继续平分引起问题的特定文件。注释掉代码,直到不执行有问题的代码。
我不确定它是否有帮助,但您也可以从 unhandledRejection
侦听器获取 Promise
作为参数,以获得更有用的输出。文档 here
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason);
// application specific logging, throwing an error, or other logic here
});