Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing for errors thrown in Mocha [duplicate]

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");
        });
    });
});
like image 952
Chris Neitzer Avatar asked Feb 19 '13 20:02

Chris Neitzer


2 Answers

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.throws(() => { iThrowError(args) }, Error);

or

assert.throws(function() { iThrowError(args) }, Error, /Error thrown/);
like image 114
red Avatar answered Oct 07 '22 22:10

red


Adding to the top answer, if you need to invoke your function as part of the test (i.e. your function should only throw an error if certain parameters are passed), you can wrap your function call in an anonymous function, or, in ES6+, you can pass your function in an arrow function expression.

// Function invoked with parameter.
// TEST FAILS. DO NOT USE.
assert.throws(iThrowError(badParam), Error, "Error thrown"); // WRONG!

// Function invoked with parameter; wrapped in anonymous function for test.
// TEST PASSES.
assert.throws(function () { iThrowError(badParam) }, Error, "Error thrown");

// Function invoked with parameter, passed as predicate of ES6 arrow function.
// TEST PASSES.
assert.throws(() => iThrowError(badParam), Error, "Error thrown");

And, just for the sake of thoroughness, here's a more literal version:

// Explicit throw statement as parameter. (This isn't even valid JavaScript.)
// TEST SUITE WILL FAIL TO LOAD. DO NOT USE, EVER.
assert.throws(throw new Error("Error thrown"), Error, "Error thrown"); // VERY WRONG!

// Explicit throw statement wrapped in anonymous function.
// TEST PASSES.
assert.throws(function () { throw new Error("Error thrown") }, Error, "Error thrown");

// ES6 function. (You still need the brackets around the throw statement.)
// TEST PASSES.
assert.throws(() => { throw new Error("Error thrown") }, Error, "Error thrown");
like image 42
Jake Avatar answered Oct 08 '22 00:10

Jake