Search code examples
node.jsmongoosenodeunit

How do I get an asynchronous result back with node unit and mongoose?


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()

Solution

  • 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:

    @db.connection.on 'open', () ->
    

    I did this (in Coffee Script):

    mongoose.connection.on 'open', () ->
    

    Second, I've reversed the order or registering the callback and making the connection.

    The resulting JavaScript:

    var mongoose = require('mongoose');
    var models = require('./models');
    var Task = models.Task;
    
    var db;
    
    module.exports = {
        setUp: function(callback) {
            try {
                //db.connection.on('open', function() {
                mongoose.connection.on('open', function() {
                    console.log('Opened connection');
                    callback();
                });
    
                db = mongoose.connect('mongodb://localhost/test_1');
                console.log('Started connection, waiting for it to open');
            }
    
            catch (err) {
                console.log('Setting up failed:', err.message);
            }
        },
    
        tearDown: function(callback) {
            console.log('In tearDown');
            try {
                console.log('Closing connection');
                db.disconnect();
                callback();
            }
    
            catch (err) {
                console.log('Tearing down failed:', err.message);
            }
        },
    
        getTasks: function(test) {
            console.log('running first test');
            Task.find({}, function (err, result) {
                if (!err) {
                    console.log('results' + result);
                    test.ok(result);
                } else {
                    console.log('error' + err);
                }
    
                test.ifError(err);
                test.done();
            });
        }
    };
    

    Models.js

    var mongoose = require('mongoose');
    
    var TaskSchema = new mongoose.Schema({
        field1: String,
        field2: Number
    });
    
    module.exports.Task = mongoose.model('Task', TaskSchema);
    

    And the resulting output:

    $ ~/node_modules/nodeunit/bin/nodeunit test.js 
    
    test.js
    Started connection, waiting for it to open
    Opened connection
    running first test
    results
    In tearDown
    Closing connection
    ✔ getTasks
    
    OK: 2 assertions (198ms)
    

    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.