Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for a throw new Error with should.js and Mocha

I've got an error thrown like so:

if (somethingBadHappened) {
    throw new Error('what were you thinking, batman?')
}

Now I want to write a test to check that this throws when expected:

should(MyClass.methodThatShouldThrow()).throws('what were you thinking, batman?')

But that actually throws the error. What am I doing wrong? Should.js docs are pretty light, since it inherits from assert.throws, but even the docs for that doesn't work in the 'should.js' way?

like image 918
brandonscript Avatar asked Dec 18 '22 22:12

brandonscript


1 Answers

As you had found out, your code execute the function which throws the error & should doesn't get a chance to catch it.

To allow proper assertion, you need to wrap the function call in an anonymous function.

should(function ()  {MyClass.methodThatShouldThrow();} ).throw('what were you thinking, batman?')
like image 134
DJ. Avatar answered Feb 12 '23 05:02

DJ.