visionmedia/mocha — Issue #230: No error output if thrown expression is a string
Author: joewhite
Created: 2012-01-21 20:32:59+00:00
State: open

If a test (or the code being tested) throws a `new Error('error message')`, Mocha's default Node-based runner will display nice details, including the error message and the stack trace. However, if the test throws some other expression -- for example, a string -- then Mocha will only display the name of the test that failed, and not the error message.

There may not be a stack trace to show in that case (since normally the stack trace is a property of the `Error` object), but Mocha should at least show the expression that was thrown.

I ran into this while testing some code that uses [Knockout](http://knockoutjs.com/), which apparently does throw plain strings in some cases (e.g. when you try to write to a computed property). Probably the best fix is to change that code so it throws an `Error` instead of a string; but as it is Mocha displays nothing, which makes it difficult to diagnose anything at all.

Repro steps:

1. Create a file called `test.js`:

describe('MyLibrary', function(){
it('handles errors', function(){
throw "Oops";
//throw new Error("Oops");
});
});

2. Run Mocha on that test. In my case, I'm running on Windows and I've installed Mocha locally via `npm install mocha`, so I do `node_modules\.bin\mocha test.js`.

Expected output: Mocha should show the name of the test that failed, followed by the expression that was thrown (in this case, the string `"Oops"`), something like this:

.

? 1 of 1 tests failed:

0) MyLibrary handles errors:
Oops

Actual output: as above, but no `Oops` is shown. The last non-blank line that Mocha outputs is `0) MyLibrary handles errors:`.

If you comment out the `throw "Oops";` line, and uncomment the `throw new Error("Oops");` line, Mocha behaves as expected, showing the error type and message (`Error: Oops`) followed by the stack trace. So this only seems to be a problem when a non-Error is thrown.