我可以从测试中连接到猫鼬吗?

时间:2015-01-05 20:39:00

标签: node.js mongodb chai

我试图运行一个使用mongoose连接到mongodb的chai测试,但它失败并且预期未定义为对象'。我使用的方法与我在正常运行的应用中使用的方法相同。我正确连接数据库了吗?

var expect = require('chai').expect;
var eeg = require('../eegFunctions');
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var mongoose = require('mongoose');
var db = mongoose.connection;

db.on('error', console.error);
db.once('open', function callback(){console.log('db ready');});

mongoose.connect('mongodb://localhost/eegControl');

test("lastShot() should return an object", function(){

    var data;
    eeg.lastShot(function(eegData){
        data = eegData;
    });
    return expect(data).to.eventually.be.an('object');        

});

1 个答案:

答案 0 :(得分:1)

你是test is asynchronous,因为与Mongo的连接是异步的,所以你需要在连接完成时进行断言:

test("lastShot() should return an object", function(done){  // Note the "done" argument

    var data;
    eeg.lastShot(function(eegData){
        data = eegData;

        // do your assertions in here, when the async action executes the callback...
        expect(data).to.eventually.be.an('object');

        done(); // tell Mocha we're done with async actions
    });

    // (no need to return anything)
});