Skip to content

armgit / mocha

Public Imported from GitHub
0

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

emit "error" on multiple calls

Tj Holowaychuk7c28c98c6408
diff --git a/lib/runnable.js b/lib/runnable.js
index 7b95effa..293fea59 100644
--- a/lib/runnable.js
+++ b/lib/runnable.js
@@ -70,6 +70,8 @@ Runnable.prototype.run = function(fn){
var self = this
, ms = this._timeout
, start = new Date
+ , finished
+ , emitted
, timer;
// timeout
@@ -79,19 +81,28 @@ Runnable.prototype.run = function(fn){
}, ms);
}
+ // called multiple times
+ function multiple() {
+ if (emitted) return;
+ emitted = true;
+ self.emit('error', new Error('done() called multiple times'));
+ }
+
+ // finished
+ function done(err) {
+ if (finished) return multiple();
+ clearTimeout(timer);
+ self.duration = new Date - start;
+ finished = true;
+ fn(err);
+ }
+
// async
if (this.async) {
try {
- this.fn(function(err){
- clearTimeout(timer);
- self.duration = new Date - start;
- fn(err);
- self.finished = true;
- });
+ this.fn(done);
} catch (err) {
- clearTimeout(timer);
- fn(err);
- this.finished = true;
+ done(err);
}
return;
}
diff --git a/test/runnable.js b/test/runnable.js
index 67ab9b96..8e9bd5d9 100644
--- a/test/runnable.js
+++ b/test/runnable.js
@@ -100,16 +100,19 @@ describe('Runnable(title, fn)', function(){
process.nextTick(done);
process.nextTick(done);
process.nextTick(done);
+ process.nextTick(done);
});
test.on('error', function(err){
++errCalls;
- console.log(err);
+ err.message.should.equal('done() called multiple times');
+ calls.should.equal(1);
+ errCalls.should.equal(1);
+ done();
});
test.run(function(){
++calls;
- console.log('called');
});
})
})