允许 chai/mocha 测试将错误冒泡到 process.on

Allowing chai/mocha tests to bubble errors to process.on

我正在编写一个捕获顶级未捕获错误的节点模块,并想为其编写一些测试。不幸的是,我最喜欢的框架似乎在故意抛出和捕获未捕获的异常方面存在一些问题。

如果我抛出异常,它就会出错并导致测试失败。

如果我抛出并捕获错误,它永远不会冒泡到 process.on('uncaughtException')

无法使用的代码 atm

it('Catches errors and return the user and line number', function(done) {
  blame.init(function (res) {
      console.log('\n\n', res, '\n\n');
    expect(true).should.equal(true);
    done();
  });

  expect(function () {
    undefinedFunction();
  }).to.throw('undefinedFunction is not defined');
});

@Louis 感谢 post。不完全是完整的修复,但需要在那里使用删除和添加事件侦听器方法。

最终解决方案

function throwNextTick(error) {
    process.nextTick(function () {
        // DO NOT MOVE FROM LINE 7
        undefinedFunction();
    })
}

describe("tattletales", function (next) {
    it("Throw a error and catch it", function (next) {
        //Removing and saving the default process handler
        var recordedError = null;
        var originalException =        process.listeners('uncaughtException').pop();
        process.removeListener('uncaughtException', originalException);

        blame.init(function (err, res) {
          // Removing the process handler my blame added
          var newException =     process.listeners('uncaughtException').pop();
          process.removeListener('uncaughtException', newException);

          // Putting back on mochas process handler
          process.listeners('uncaughtException').push(originalException);

          assert.equal(res.error, 'ReferenceError: undefinedFunction is not defined');
          next();
       });
       throwNextTick();
   })
})