Skip to content

Commit a24683f

Browse files
Zirakcraigtaub
authored andcommitted
Throw a descriptive error when a non-function is given to a runnable (#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.)
1 parent 579fd09 commit a24683f

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

lib/runnable.js

+9
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,15 @@ Runnable.prototype.run = function(fn) {
338338
// for .resetTimeout()
339339
this.callback = done;
340340

341+
if (this.fn && typeof this.fn.call !== 'function') {
342+
done(
343+
new TypeError(
344+
'A runnable must be passed a function as its second argument.'
345+
)
346+
);
347+
return;
348+
}
349+
341350
// explicit async with `done` argument
342351
if (this.async) {
343352
this.resetTimeout();

test/unit/runnable.spec.js

+14
Original file line numberDiff line numberDiff line change
@@ -670,6 +670,20 @@ describe('Runnable(title, fn)', function() {
670670
});
671671
});
672672
});
673+
674+
describe('when fn is not a function', function() {
675+
it('should throw an error', function() {
676+
var runnable = new Runnable('foo', 4);
677+
678+
runnable.run(function(err) {
679+
expect(
680+
err.message,
681+
'to be',
682+
'A runnable must be passed a function as its second argument.'
683+
);
684+
});
685+
});
686+
});
673687
});
674688

675689
describe('#isFailed()', function() {

0 commit comments

Comments
 (0)