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

Can I connect to mongoose from within a test?

我正在尝试使用 mongoose 运行一个连接到 mongodb 的 chai 测试,但它因 'expected undefined to be an object' 而失败。我使用的方法与我在正常运行的应用程序中使用的方法相同。我是否正确连接到数据库?

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

});

你是 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)
});