6awmha
Last Updated: February 25, 2016
·
2.781K
· sleepyfox
E7b5b069781ecc84610ef1d1fdea41af

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.

Say Thanks
Respond

1 Response
Add your response

10182
E7b5b069781ecc84610ef1d1fdea41af

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 ·
Filed Under