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.
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.
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With