3

从 REPL 连接工作正常:

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

返回:

{ 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

但是从 Mocha 测试套件连接不起作用:

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' );
});

返回:

$ mocha
connecting...



  0 passing (0 ms)

有谁知道为什么这不起作用?

4

1 回答 1

4

您的套件中有任何测试吗?如果不是,似乎 mocha 在猫鼬有机会连接之前就退出了。摩卡页面上列出的功能之一是

自动退出以防止活动循环“挂起”

这可能与它有关。您可以尝试在测试套件的 before 方法中连接到 mongoose,例如

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);
        });
    });
});
于 2013-08-29T12:31:50.573 回答