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

标签 node.js exception testing mocha.js chai

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

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

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

无法使用的自动取款机

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 谢谢你的帖子。不完全是完整的修复,但需要在那里使用删除和添加事件监听器方法。

最终解决方案

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

关于node.js - 允许 chai/mocha 测试将错误冒泡到 process.on,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28971165/

相关文章:

windows - Node-webkit 应用程序中的手指扫描仪

node.js - "Client network socket disconnected before secure TLS connection was established", Node 10

node.js - 如何使用没有快捷方式蓝图的 REST 搜索 sails.js 模型?

java - 直接使用上下文获取的Spring/Mock组件

node.js - Node JS、Redis 和 Heroku

C# : catch all errors/exceptions of a mixed managed/unmanaged process

安卓。异常处理

java - Java 8 函数中的运行时异常

java - 如何使用 Selenium 测试单击链接后任何超链接的颜色变化

django - 如何启动 Django 可重用应用程序的测试?