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
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 committed Dec 20, 2019
1 parent d9f5079 commit 185561c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/runnable.js
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
10 changes: 10 additions & 0 deletions test/unit/runnable.spec.js
Expand Up @@ -670,6 +670,16 @@ 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, 'not to match', /fn\.call/);
});
});
});
});

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

0 comments on commit 185561c

Please sign in to comment.