Dan Ross
Dan Ross

Reputation: 3691

Can't connect to mongodb from mocha test

Connecting from the REPL works fine:

> var mongoose=require('mongoose');
undefined
> mongoose.connect('mongodb://localhost/test', function(error) {
... console.log( 'connected\n%s\n', error );
... });

returns:

{ connections: 
   [ { base: [Circular],
       collections: {},
       models: {},
       replica: false,
       hosts: null,
       host: 'localhost',
       port: 27017,
       user: undefined,
       pass: undefined,
       name: 'test',
       options: [Object],
       _readyState: 2,
       _closeCalled: false,
       _hasOpened: false,
       _listening: false,
       _events: {},
       db: [Object] } ],
  plugins: [],
  models: {},
  modelSchemas: {},
  options: {} }
> connected # Yes!
undefined

But connecting from a Mocha test suite does not work:

var mongoose = require( 'mongoose' );
console.log( 'connecting...' );

mongoose.connect( 'mongodb://localhost/test', function( error ) {
    if( error) console.error( 'Error while connecting:\n%\n', error );

    console.log( 'connected' );
});

returns:

$ mocha
connecting...



  0 passing (0 ms)

Does anyone know why this not working?

Upvotes: 3

Views: 2529

Answers (1)

Brett
Brett

Reputation: 3885

Do you have any tests in your suite? If not it seems like mocha exits before mongoose gets a chance to connect. One of the features listed on the mocha page is

auto-exit to prevent "hanging" with an active loop

which may have something to do with it. You could try connecting to mongoose in the before method of your test suite e.g.

describe('test suite', function() {
    before(function(done) {
        mongoose.connect('mongodb://localhost/test', function(error) {
            if (error) console.error('Error while connecting:\n%\n', error);
            console.log('connected');
            done(error);
        });
    });
});

Upvotes: 4

Related Questions