首页 > 解决方案 > 来自本机代码的 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。

那么问题来了:如何缩小范围以找到有问题的代码?

标签: node.jsdebuggingpromisemocha.js

解决方案


我不确定它是否会有所帮助,但您也可以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
});

推荐阅读