Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix leaking global 'uncaughtException' handler #4147

Merged
merged 2 commits into from Jan 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 14 additions & 7 deletions lib/runner.js
Expand Up @@ -800,7 +800,7 @@ Runner.prototype.runSuite = function(suite, fn) {
};

/**
* Handle uncaught exceptions.
* Handle uncaught exceptions within runner.
*
* @param {Error} err
* @private
Expand Down Expand Up @@ -893,6 +893,17 @@ Runner.prototype.uncaught = function(err) {
this.abort();
};

/**
* Handle uncaught exceptions after runner's end event.
*
* @param {Error} err
* @private
*/
Runner.prototype.uncaughtEnd = function uncaughtEnd(err) {
if (err instanceof Pending) return;
throw err;
};

/**
* Run the root suite and invoke `fn(failures)`
* on completion.
Expand Down Expand Up @@ -940,16 +951,12 @@ Runner.prototype.run = function(fn) {
this.on(constants.EVENT_RUN_END, function() {
debug(constants.EVENT_RUN_END);
process.removeListener('uncaughtException', uncaught);
process.on('uncaughtException', function(err) {
if (err instanceof Pending) {
return;
}
throw err;
});
process.on('uncaughtException', self.uncaughtEnd);
fn(self.failures);
});

// uncaught exception
process.removeListener('uncaughtException', self.uncaughtEnd);
process.on('uncaughtException', uncaught);

if (this._delay) {
Expand Down
12 changes: 12 additions & 0 deletions test/integration/fixtures/uncaught/listeners.fixture.js
@@ -0,0 +1,12 @@
'use strict';

const assert = require('assert');
const mocha = require("../../../../lib/mocha");

for (let i = 0; i < 15; i++) {
const r = new mocha.Runner(new mocha.Suite("" + i, undefined));
r.run();
}

assert.equal(process.listenerCount('uncaughtException'), 1);
assert.equal(process.listeners('uncaughtException')[0].name, 'uncaughtEnd');
12 changes: 12 additions & 0 deletions test/integration/uncaught.spec.js
Expand Up @@ -86,4 +86,16 @@ describe('uncaught exceptions', function() {
done();
});
});

it('removes uncaught exceptions handlers correctly', function(done) {
run('uncaught/listeners.fixture.js', args, function(err, res) {
if (err) {
return done(err);
}

expect(res, 'to have passed').and('to have passed test count', 0);

done();
});
});
});