8

One of the points of using NodeUnit is to write new functions and test them often. Problem is, if one of the tested functions throws an error (including JS runtime errors), the error is not shown to the user. Here is the simplest possible test case: (Note that a.b.c.d will cause a runtime error)

exports.all = {
  one: function( test ){
    test.done();
  },

  two: function( test ){
    as( function( err, res ){
      test.done();
    });
  },
}


function as( callback ){
  process.nextTick( function() {
    a = testMe();
    callback( null, a );
  });
}

function testMe(){
  a.b.c.d.e = 100;
  return 10;
}

However, testMe() might be a new function I am developing. An uninitialised variable, or anything, will just fall silent.

Merc
  • 16,277
  • 18
  • 79
  • 122

1 Answers1

13

Add your own uncaught exception handling to your test file either via the uncaughtException event:

process.on('uncaughtException', function(err) {
  console.error(err.stack);
});

Or by creating a domain and adding process to it (or whatever event emitter(s) your tests use) so that you can catch the errors that occur within your use of process.nextTick:

var dom = require('domain').create();
dom.add(process);
dom.on('error', function(err) {
    console.error(err.stack);
});

Either way, you'll then get console output that looks like:

ReferenceError: a is not defined
    at testMe (/home/test/test.js:24:3)
    at /home/test/test.js:18:9
    at process._tickDomainCallback (node.js:459:13)
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • The best 50 points I've ever given to somebody... I don't suppose you'd like to share a little more about this? I should know more about error handling at this point, shame on me. Given that I don't want to touch domains yet, the manual says: "Emitted when an exception bubbles all the way back to the event loop." When would that happen exactly? What does node actually *do* to fire that event? does it fire it for every event listener ever registered? I am a little confused! – Merc Nov 18 '13 at 05:30
  • Ah, answering myself, I get it. This is for when something `throws`, and there is no `catch` for it. So, effectively there is an uncaught error, which "bubbles up". At that point, nodejs fires the 'uncaughtException" event for the process object. BUT, in my code above, the exception is not caught at all -- hence the bubbling up, and the event in `process`. Did I get it right? – Merc Nov 18 '13 at 05:35
  • @Merc Glad it helped you out. Yeah, that's the gist of it. – JohnnyHK Nov 18 '13 at 15:00
  • 2
    Yeah! They really should build this into Nodeunit. – Brad Apr 12 '15 at 23:54
  • It's bizarre to me that nodeunit doesn't report uncaught exceptions by default. What is the logic here? – starsinmypockets Aug 16 '15 at 00:11