Testing JS exceptions with Mocha/Chai

TheDelChop picture TheDelChop · Sep 20, 2013 · Viewed 28k times · Source

Trying to test some code that throws an exception with Mocha/Chai, but having no luck, here's the simple code I'm trying to test:

class window.VisualizationsManager

  test: ->
    throw(new Error 'Oh no')

Here is my test:

describe 'VisualizationsManager', ->

  it 'does not permit the construction of new instances', ->

    manager = new window.VisualizationsManager

    chai.expect(manager.test()).to.throw('Oh no')

However, when I run the spec, the test fails and throws the exception.

Failure/Error: Oh no

what am I doing wrong here?

Answer

Idan Wender picture Idan Wender · Sep 21, 2013

Either pass the function:

chai.expect(manager.test).to.throw('Oh no');

Or use an anonymous function:

chai.expect(() => manager.test()).to.throw('Oh no');

See the documentation on the throw method to learn more.