【问题标题】:Can't connect to mongodb from mocha test无法从 mocha 测试连接到 mongodb
【发布时间】:2013-09-01 04:18:54
【问题描述】:

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

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

【问题讨论】:

    标签: mongodb mongoose mocha.js


    【解决方案1】:

    您的套件中有任何测试吗?如果不是,似乎 mocha 在猫鼬有机会连接之前就退出了。 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);
            });
        });
    });
    

    【讨论】:

    • 当我运行这段代码时,我得到Typeerror: done is not a function,见stackoverflow.com/questions/46294310/…
    • 放置完成();在 mongoose.connect 函数之外,它可以访问 done 方法。
    猜你喜欢
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 2016-07-31
    • 2023-03-23
    相关资源
    最近更新 更多