How do I get an asynchronous result back in nodeunit and mongoose? I've tried the following code and it seems to hang on the database callback never returning a result or err.
mongoose = require "mongoose"
models = require "../Services/models"
Task = models.Task
module.exports =
setUp: (callback) ->
try
@db = mongoose.connect "myConnString"
console.log 'Started connection, waiting for it to open'
@db.connection.on 'open', () ->
console.log 'Opened connection'
callback()
catch err
console.log 'Setting up failed:', err.message
tearDown: (callback) ->
console.log 'In tearDown'
try
console.log 'Closing connection'
@db.disconnect()
callback()
catch err
console.log 'Tearing down failed:', err.message
"get tasks" : (test) ->
console.log 'running first test'
Task.find {}, (err, result) ->
if not err
console.log 'results' + result
test.ok(result)
else
console.log 'error' + err
test.ifError(err)
test.done()
I've ported the test script from Coffee Script to JavaScript and ran it in NodeUnit, see below.
There were two things I have changed though. First, instead of:
I did this (in Coffee Script):
Second, I've reversed the order or registering the callback and making the connection.
The resulting JavaScript:
Models.js
And the resulting output:
I do have to note that when MongoDB was not running/not connectable, the tests were failing like you stated. So you might want to check your connection string as well.