Force Mocha test to fail?

Using Mocha, I am attempting to test whether a constructor throws an error. I haven't been able to do this using the expect syntax, so I'd like to do the following:

it('should throw exception when instantiated', function() {
  try {
    new ErrorThrowingObject();
    // Force the test to fail since error wasn't thrown
  }
  catch (error) {
   // Constructor threw Error, so test succeeded.
  }
}

Is this possible?

should.js

Using the should.js library with should.fail

var should = require('should')
it('should fail', function(done) {
  try {
      new ErrorThrowingObject();
      // Force the test to fail since error wasn't thrown
       should.fail('no error was thrown when it should have been')
  }
  catch (error) {
   // Constructor threw Error, so test succeeded.
   done();
  }
});

Alternative you can use the should throwError

(function(){
  throw new Error('failed to baz');
}).should.throwError(/^fail.*/)

Chai

And with chai using the throw api

var expect = require('chai').expect
it('should fail', function(done) {
  function throwsWithNoArgs() {
     var args {} // optional arguments here
     new ErrorThrowingObject(args)
  }
  expect(throwsWithNoArgs).to.throw
  done()
});

You can try using Chai's throw construct. For example:

expect(Constructor).to.throw(Error);

Chai now has

should.fail() and expect.fail()

https://github.com/chaijs/chai/releases/tag/2.1.0

If you are using should.js you can do (new ErrorThrowingObject).should.throw('Option Error Text or Regular Expression here')

If you don't want to should a separate library, you could also do something like this:

it('should do whatever', function(done) {
    try {
        ...
    } catch(error) {
        done();
    }
}

This way, you know the error is caught if the test finishes. Otherwise, you will get a timeout error.

Chai's Assert API contains a fail() method. The documentation describes four parameters, but calling assert.fail() without any parameters fails the test as desired.

This can be used within try { .. } catch (e) { .. } blocks as described in the question, or in .then( .. ).catch( .. ) blocks of promises.

http://chaijs.com/api/assert/