Last Updated: February 25, 2016
·
3.199K
· sleepyfox

Expecting an exception in Jasmine-node

It may not be immediately obvious why when you write some coffeescript code using jasmine-node like:

it 'myFunction should throw an exception if passed 3', ->
  myFunction = ->
    throw new Error 'argument cannot be 3'
  expect(myFunction 3).toThrow 'argument cannot be 3'

that it doesn't work, instead showing:

Failures:

1) myFunction should throw an exception if passed 3
Message:
  Error: argument cannot be 3
Stacktrace:
  Error: argument cannot be 3
    at myFunction...

Perhaps we could put a try/catch clause in our code, but then what's the point of using the matcher toThrow()?

The key here is to realise that the matcher is expecting a function to evaluate, but instead we have passed it the result of evaluating a function - so instead we need to wrap our evaluation with a lambda like so:

it 'myFunction should throw an exception if passed 3', ->
  expect( -> myFunction 3).toThrow 'argument cannot be 3'

This now works as expected.

1 Response
Add your response

Postscript: If you want to do this in Chai.js it would look like this:

it 'should throw an XYZ error', ->

(-> myFunction 3).should.throw 'XYZ'

over 1 year ago ·