【问题标题】:Allowing chai/mocha tests to bubble errors to process.on允许 chai/mocha 测试将错误冒泡到 process.on
【发布时间】:2015-03-10 18:17:04
【问题描述】:

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

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

如果我抛出并捕获错误,它永远不会冒泡到 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');
});

【问题讨论】:

标签: node.js exception testing mocha.js chai


【解决方案1】:

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

最终解决方案

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();
   })
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2017-10-23
    • 1970-01-01
    • 2017-11-14
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多