Neablis
Neablis

Reputation: 914

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

I am writing a node module that catches top level uncaught errors and want to write some tests for it. Unfortunately my favorite framework seems to have some issues with intentionally throwing and catching uncaught exceptions.

If I throw the exception, it errors and fails the test then.

If I throw and catch the error, it never bubbles to the process.on('uncaughtException')

The code atm that isn't working

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

Upvotes: 1

Views: 499

Answers (1)

Neablis
Neablis

Reputation: 914

@Louis Thanks for the post. Wasn't exactly the full fix but needed to use there removing and adding of event listener methods.

Final Solution

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

Upvotes: 1

Related Questions