Mongoose保存在app中工作但不在Mocha中工作

时间:2013-06-24 23:09:47

标签: node.js mongoose mocha

我正在尝试为我正在进行的项目编写一些基本的单元测试,作为一种学习经历,并且遇到了令我难过的事情。

基本上,我可以在独立的节点应用程序中运行下面的代码,代码创建新的数据库并按预期插入记录。如果我然后使用相同的代码并在节点中的mocha测试中运行它,我看到mongod报告一个新连接,但没有创建DB并且没有插入记录(并且没有报告错误)。

任何想法发生了什么(猫鼬代码直接来自猫鼬网站)。

独立节点应用程序(server.js)

var mg = require( 'mongoose' );

mg.connect( 'mongodb://localhost/cat_test' );

var Cat = mg.model( 'Cat', { name: String } );
var kitty = new Cat({ name: 'Zildjian' });
kitty.save( function( err ){
    if ( err ){
        console.log( err );
    }
    process.exit();
});

摩卡测试(test.js)

describe( 'Saving models', function(){
    it( 'Should allow models to be saved to the database', function(){
        var mg = require( 'mongoose' );

        mg.connect( 'mongodb://localhost/cat_test' );

        var Cat = mg.model( 'Cat', { name: String } );
        var kitty = new Cat({ name: 'Zildjian' });
        kitty.save( function( err ){
            if ( err ){
                console.log( err );
            }
            done();
        });
    });
});

思考?我猜这是非常明显的,我忽略了但是我很难过。

1 个答案:

答案 0 :(得分:3)

我想出来了 -

我需要将done参数添加到它的调用 -

摩卡测试 - 修订

// The parameter below was left off before, which caused the test to run without
// waiting for results.
describe( 'Saving models', function( done ){
    it( 'Should allow models to be saved to the database', function(){
        var mg = require( 'mongoose' );

        mg.connect( 'mongodb://localhost/cat_test' );

        var Cat = mg.model( 'Cat', { name: String } );
        var kitty = new Cat({ name: 'Zildjian' });
        kitty.save( function( err ){
            if ( err ){
                console.log( err );
            }
            done();
        });
    });
});
相关问题