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.
Written by Sleepyfox
Related protips
1 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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Node
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#