Skip to content

Commit

Permalink
Improve assertion messages in uncaught exceptions
Browse files Browse the repository at this point in the history
Wrap all assert.* methods in a try/catch that appends the
current test to the Error object and rethrows.

This allows us to get the corresponding Test object in the
`uncaughtException` event.

Before:

   uncaught undefined: AssertionError: 'blah' === 'blahs'
    at Blah.<anonymous> (/home/user/test.js:15:17)
    ...

After:

   test.js testing blah(): AssertionError: 'blah' === 'blahs'
    at Blah.<anonymous> (/home/user/test.js:15:17)
    ...
  • Loading branch information
danielbeardsley committed Oct 8, 2012
1 parent 665f47c commit fc43ba6
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
25 changes: 21 additions & 4 deletions bin/expresso
Expand Up @@ -549,6 +549,24 @@ assert.response = function(server, req, res, msg) {
}
};

/**
* Custom assert module that tacks on the current test to every error
*/
var customAssert = { __proto__: assert };
Object.keys(assert).forEach(function (method) {
customAssert[method] = function () {
try {
return assert[method].apply(assert, arguments);
} catch (err) {
// 'this' is this assert object from the test
if (this._test) {
err._test = this._test;
}
throw err;
}
};
});

/**
* Pad the given string to the maximum width provided.
*
Expand Down Expand Up @@ -885,7 +903,7 @@ function Test(options) {
this._failed = [];
this._pending = [];
this._beforeExit = [];
this.assert = { __proto__: assert, _test: this };
this.assert = { __proto__: customAssert, _test: this };

var test = this;
process.on('beforeExit', function() {
Expand Down Expand Up @@ -976,11 +994,10 @@ Test.prototype.runParallel = function() {
Test.prototype.error = function(err) {
if (!err._reported) {
++failures;
var test = err._test || this;
var name = err.name,
stack = err.stack ? err.stack.replace(err.name, '') : '',
label = this.title === 'uncaught'
? this.title
: this.suite + ' ' + this.title;
label = test.suite + ' ' + test.title;
print('\n [bold]{' + label + '}: [red]{' + name + '}' + stack + '\n');
err._reported = true;
}
Expand Down
8 changes: 8 additions & 0 deletions test/local-assert.test.js
Expand Up @@ -5,6 +5,14 @@ exports['first'] = function(beforeExit, assert) {
process.nextTick(function() {
assert.equal(assert._test.suite, 'local-assert.test.js');
assert.equal(assert._test.title, 'first');
try {
var error = false;
assert.ok(false);
} catch (err) {
assert.equal(err._test, assert._test);
error = true;
}
assert.ok(error);
});
};

Expand Down

0 comments on commit fc43ba6

Please sign in to comment.