node.js - 来自本机代码的 mocha 测试中未处理的拒绝
问题描述
我在 mocha 测试中收到“未处理的拒绝”消息,但我不知道问题的确切根源是什么,因为这是异步发生的。
我知道我可以为全局 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 模块中。如果我尝试只运行发生此跟踪的测试,它根本不会发生。这可能是因为“早些时候”在某个地方设立了一个失控的承诺。指定的 /tmp/ 路径不存在于测试代码或实际实现代码中的任何位置。testfile.json 确实存在,但不在该路径中。
我正在使用节点 6.5.0 运行 mocha 3.5.3。
那么问题来了:如何缩小范围以找到有问题的代码?
解决方案
我不确定它是否会有所帮助,但您也可以Promise
从侦听器中获取作为参数,unhandledRejection
以获取更多有用的输出。文档在这里
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason);
// application specific logging, throwing an error, or other logic here
});
推荐阅读
- c# - 我可以在我的 Mac Catalina 10.15.4 上安全地安装 Mono 并在需要时配置 Mono 32 吗?
- matplotlib - 在 matplotlib 中使用粗体安装字体
- spring - 从 springfox 迁移到 springdoc 时为 Null ApiResponse
- python - Python:从文本文件中读取 URL 并保存结果错误
- arrays - 创建一个扩展数组的类
- swiftui-navigationlink - 放置在 NavigationLink 中时,颜色视图不可见
- javascript - $.getJSON() 没有被触发
- c# - 在c#中的嵌套JSON对象内反序列化嵌套JSON数组?
- vue.js - VueJS 使用路由查询渲染动态组件
- c - 由于未知的参考错误,程序无法运行