我可以从testing中连接mongoose吗?

我正在尝试使用mongoose运行连接到mongodb的chaitesting,但是由于“预期未定义为对象”而失败。 我正在使用function相同的方法。 我是否正确连接到数据库?

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

你的testing是asynchronous的,因为到Mongo的连接是asynchronous的,所以你需要在连接完成时进行断言:

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