Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

Fix #1669: catch uncaught errors outside test suite execution

Daniel St. Julesf22ab537be95
diff --git a/lib/runner.js b/lib/runner.js
index 39571316..8c2478ad 100644
--- a/lib/runner.js
+++ b/lib/runner.js
@@ -7,6 +7,7 @@ var Pending = require('./pending');
var utils = require('./utils');
var inherits = utils.inherits;
var debug = require('debug')('mocha:runner');
+var Runnable = require('./runnable');
var filter = utils.filter;
var indexOf = utils.indexOf;
var keys = utils.keys;
@@ -64,6 +65,7 @@ function Runner(suite, delay) {
this._abort = false;
this._delay = delay;
this.suite = suite;
+ this.started = false;
this.total = suite.total();
this.failures = 0;
this.on('test end', function(test) {
@@ -653,7 +655,20 @@ Runner.prototype.uncaught = function(err) {
err.uncaught = true;
var runnable = this.currentRunnable;
+
if (!runnable) {
+ runnable = new Runnable('Uncaught error outside test suite');
+ runnable.parent = this.suite;
+
+ if (this.started) {
+ this.fail(runnable, err);
+ } else {
+ // Can't recover from this failure
+ this.emit('start');
+ this.fail(runnable, err);
+ this.emit('end');
+ }
+
return;
}
@@ -712,6 +727,7 @@ Runner.prototype.run = function(fn) {
}
function start() {
+ self.started = true;
self.emit('start');
self.runSuite(rootSuite, function() {
debug('finished running');
diff --git a/test/integration/fixtures/options/delay-fail.js b/test/integration/fixtures/options/delay-fail.js
new file mode 100644
index 00000000..1475c918
--- /dev/null
+++ b/test/integration/fixtures/options/delay-fail.js
@@ -0,0 +1,5 @@
+setTimeout(function() {
+ throw new Error('oops');
+ it('test', function() {});
+ run();
+}, 100);
diff --git a/test/integration/options.js b/test/integration/options.js
index db371091..52eff4b4 100644
--- a/test/integration/options.js
+++ b/test/integration/options.js
@@ -96,6 +96,20 @@ describe('options', function() {
done();
});
});
+
+ it('should throw an error if the test suite failed to run', function(done) {
+ run('options/delay-fail.js', args, function(err, res) {
+ assert(!err);
+ assert.equal(res.stats.pending, 0);
+ assert.equal(res.stats.passes, 0);
+ assert.equal(res.stats.failures, 1);
+
+ assert.equal(res.failures[0].title,
+ 'Uncaught error outside test suite');
+ assert.equal(res.code, 1);
+ done();
+ });
+ });
});
describe('--grep', function() {