Skip to content

Commit

Permalink
Throw a descriptive error when a non-function is given to a runnable (#…
Browse files Browse the repository at this point in the history
…4133)

Given a test such as:

```js
it('foobars', 4);
```

mocha used to throw the following error: `fn.call is not a function`.

While technically true, I have personally spent some minutes of my life chasing
what looked like a bug in the test itself, and not in the call to `it`. A more
descriptive error message helps bring attention to where the problem originates.

(Thanks to [ssube](https://github.com/ssube) for helping with the error wording.)
  • Loading branch information
Zirak authored and craigtaub committed Jan 19, 2020
1 parent 579fd09 commit a24683f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/runnable.js
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,15 @@ Runnable.prototype.run = function(fn) {
// for .resetTimeout()
this.callback = done;

if (this.fn && typeof this.fn.call !== 'function') {
done(
new TypeError(
'A runnable must be passed a function as its second argument.'
)
);
return;
}

// explicit async with `done` argument
if (this.async) {
this.resetTimeout();
Expand Down
14 changes: 14 additions & 0 deletions test/unit/runnable.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -670,6 +670,20 @@ describe('Runnable(title, fn)', function() {
});
});
});

describe('when fn is not a function', function() {
it('should throw an error', function() {
var runnable = new Runnable('foo', 4);

runnable.run(function(err) {
expect(
err.message,
'to be',
'A runnable must be passed a function as its second argument.'
);
});
});
});
});

describe('#isFailed()', function() {
Expand Down

0 comments on commit a24683f

Please sign in to comment.