I would like to test that the following function performs as expected:
function throwNextTick(error) {
process.nextTick(function () {
throw error;
});
}
Here is my attempt:
describe("throwNextTick", function () {
it("works as expected", function (next) {
var error = new Error("boo!");
var recordedError = null;
process.once("uncaughtException", function (error) {
recordedError = error;
});
throwNextTick(error);
process.nextTick(function () {
recordedError.should.be(error);
next();
});
});
});
But mocha seems to want to keep any errors to itself, and fail my test when it gets them:
C:\Users\ddenicola\Programming (Synced)\pubit>mocha test/basicTest.js
throwNextTick
0) works as expected
? 1 of 1 tests failed:
1) throwNextTick works as expected:
Error: boo!
at Test.fn (C:\Users\ddenicola\Programming (Synced)\pubit\test\basicTest.js:11:21)
at Test.run (C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runnable.js:144:15)
at Runner.runTest (C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:271:10)
at C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:315:12
at next (C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:199:14)
at C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:208:7
at next (C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:157:23)
at Array.0 (C:\Users\ddenicola\AppData\Roaming\npm\node_modules\mocha\lib\runner.js:176:5)
at EventEmitter._tickCallback (node.js:192:40)
Any ideas?
Update: Courtesy of casey-foster in a comment below:
Old answer:
The secret lies in process.listeners('uncaughtException'):
http://nodejs.org/docs/latest/api/events.html#emitter.listeners
Simply remove the mocha listener, add your own, then reattach the mocha listener.
See below:
If your async code is executed within a domain - and that is often the case - you need to change the error listener on the domain instead of the process.
For that you can use:
Base on timoxley & Casey Foster, in node v6++