Skip to content

Instantly share code, notes, and snippets.

@lennym
Created August 11, 2016 14:52
Show Gist options
  • Save lennym/0d74f3c4f8e32b2dcabb1678b869cd34 to your computer and use it in GitHub Desktop.
Save lennym/0d74f3c4f8e32b2dcabb1678b869cd34 to your computer and use it in GitHub Desktop.
const assert = require('assert');
const sandbox = require('./sandbox');
function myAsyncFn (callback) {
setTimeout(() => {
callback(null, 5);
}, 500);
}
describe('async things', () => {
it('does not report nicely', (done) => {
myAsyncFn((err, value) => {
assert.equal(value, 4); // blows up with an unhandled exception crashing mocha process
done();
});
});
it('uses sandbox, so reports nicely', (done) => {
myAsyncFn(sandbox(done, (err, value) => {
assert.equal(value, 4); // fails with a "nice" mocha failure report
done();
}));
});
});
/**
* Helper function to allow mocha to nicely report errors in assertions
* Normally an error thrown in an async callback will result in an
* unhandledException. By wrapping in a try/catch block and passing any
* assertion errors back to the mocha callback we can utilise mocha's
* error reporting properly.
*/
module.exports = function (done, callback) {
return function () {
try {
callback.apply(null, arguments);
} catch (e) {
done(e);
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment