Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test with Mocha for throw in asynchronous function

I try to test the validation of my MongoDB Mangoose model using the mocha framework.

describe 'User', ->
  describe 'create', ->
    it 'should reject a user with an already existing mail', (done) ->
      User.create
        mail: "[email protected]"
      , (err) ->
          if err then done() else done(false)

I expect a validation error issues by Mongoose, because this mail is already taken, but the field was marked as unique.

How can I test for the specific error? I thought the most cleanest way would be to use should.throws(callback, message-regexp), however, this doesn't work because Model#create is asynchronous.

References (that didn't helped me)

  • Testing for an Asynchronous throw in Mocha
  • http://shouldjs.github.io/#should-throws
like image 906
rriemann Avatar asked Mar 01 '26 22:03

rriemann


1 Answers

The problem is with the done() callback. The first parameter checks for an error, and it must be true-y in case of error. In your code, you're always passing false-y values, which means that the test run successfully.

In your case, you want to use:

if err then done() else done(true)

Instead of true, you can add a string or anything else.

EDIT

Async functions normally do not throw errors. Errors are thrown when you actually use an exception (throw new Error(...)). Mongoose, instead, just calls the callback passing a non-false value to the err parameter (the first one). So, just check if err.toString() or err.message match your search string.

For example, on your callback (assuming you're using Should.js, as your comments makes me think; otherwise, convert this to whatever other framework you implemented)

should(err).be.not.empty
err.toString().should.match(/ValidationError/)

(that's all!)

like image 188
ItalyPaleAle Avatar answered Mar 03 '26 11:03

ItalyPaleAle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!