Chris Neitzer Chris Neitzer - 1 year ago 113
Javascript Question

Testing for errors thrown in Mocha

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");

red red
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download