4

Using Chai with Mocha, what syntax would I use to assert that an error is thrown when using the new keyword to execute a constructor function? I get an error when I use the following:

assert.throw(new SomeFunction, Error);

This returns:

AssertionError: expected { Object () } to be a function

Spencer Carnage
  • 2,056
  • 2
  • 28
  • 41

1 Answers1

10

Pass a function to assert.throw:

assert.throw(function () {
    new SomeFunction()
}, Error);

The reason what you had did not work is that the new SomeFunction is interpreted as new SomeFunction() and executed before assert.throw executes. So you end up running assert.throw with an object which is an instance of SomeFunction, rather than with a function that instantiates an object.

Louis
  • 146,715
  • 28
  • 274
  • 320