Testing for errors thrown in Mocha

Chris Neitzer picture Chris Neitzer · Feb 19, 2013 · Viewed 94.8k times · Source

I'm hoping to find some help with this problem. I'm trying to write tests for an application I am writing. I have distilled the problem in to the following sample code. I want to test that an error was thrown. I'm using Testacular as a test runner with mocha as the framework and chai as the assertion library. The tests run, but the test fails because an error was thrown! Any help is greatly appreciated!

function iThrowError() {
    throw new Error("Error thrown");
}

var assert = chai.assert,
    expect = chai.expect;
describe('The app', function() {
    describe('this feature', function() {
        it("is a function", function(){
            assert.throw(iThrowError(), Error, "Error thrown");
        });
    });
});

Answer

red picture red · Jul 22, 2013

You're not passing your function to assert.throws() the right way.

The assert.throws() function expects a function as its first parameter. In your code, you are invoking iThrowError and passing its return value when calling assert.throws().

Basically, changing this:

assert.throws(iThrowError(), Error, "Error thrown");

to this:

assert.throws(iThrowError, Error, "Error thrown");

should solve your problem.

With args:

assert.throw(() => { iThrowError(args) }, Error);

or

assert.throw(function() { iThrowError(args) }, Error, /Error thrown/);