Skip to content

Commit

Permalink
Fail when test resolution method is overspecified
Browse files Browse the repository at this point in the history
Users may register `Runnable`s as asynchronous in one of two ways:

- Via callback (by defining the body function to have an arity of one)
- Via promise (by returning a Promise object from the body function)

When both a callback function is specified *and* a Promise object is
returned, the `Runnable`'s resolution condition is ambiguous.
Practically speaking, users are most likely to make this mistake as they
transition between asynchronous styles.

Currently, Mocha silently prefers the callback amd ignores the Promise
object. Update the implementation of the `Runnable` class to fail
immediately when the test resolution method is over-specified in this
way.
  • Loading branch information
jugglinmike authored and Christopher Hiller committed Oct 29, 2014
1 parent b7edc81 commit ac4b2e8
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/runnable.js
Expand Up @@ -182,7 +182,8 @@ Runnable.prototype.run = function(fn){
, start = new Date
, ctx = this.ctx
, finished
, emitted;
, emitted
, result;

// Some times the ctx exists but it is not runnable
if (ctx && ctx.runnable) ctx.runnable(this);
Expand Down Expand Up @@ -214,7 +215,7 @@ Runnable.prototype.run = function(fn){
this.resetTimeout();

try {
this.fn.call(ctx, function(err){
result = this.fn.call(ctx, function(err){
if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
if (null != err) {
if (Object.prototype.toString.call(err) === '[object Object]') {
Expand All @@ -225,6 +226,10 @@ Runnable.prototype.run = function(fn){
}
done();
});

if (result && typeof result.then === 'function') {
return done(new Error('Asynchronous resolution method is overspecified. Specify a callback *or* return a Promise, not both.'));
}
} catch (err) {
done(err);
}
Expand Down
8 changes: 8 additions & 0 deletions test/acceptance/overspecified-async.js
@@ -0,0 +1,8 @@
describe('overspecified asynchronous resolution method', function() {
it('should fail when multiple methods are used', function(done) {
setTimeout(done, 0);

// uncomment
// return { then: function() {} };
});
});

0 comments on commit ac4b2e8

Please sign in to comment.