保持Supertest直到API初始化

我使用一个使用MongoDB的快速API的Supertest进行摩卡testing。 MongoDB正在运行,但是我目前正在使用Supertest来使用Express API,而不是单独启动它(我更喜欢这种方法):

var request = require( 'supertest' ); var chai = require( 'chai' ); var api = require( '../../server/api.js' ); chai.should(); describe( "/api/lists", function() { it( "should be loaded", function() { api.should.exist; } ); it( "should respond with status 200 ", function( done ) { request( api ) .get( '/api/lists' ) .expect( 200, done ); } ); } ); 

testing运行时失败:

 TypeError: Cannot call method 'collection' of undefined at app.get.listId (/my/path/api.js:63:5) 

我怀疑supertest是在MongoDB连接build立之前在API上运行testing的。 什么是正确的方式让它暂缓,直到我的API完全初始化?

我想,如果我在快速启动后通过Grunt进行testing,那就没事了,但是由于Supertest可以代表我开始expression,所以我希望能够以这种方式开始。

您可以执行以下操作:

 describe( "/api/lists", function() { before(function(done) { mongoose.connect(config.db.mongodb); done(); }); it( "should be loaded", function() { .... 

我运行我的testing使用Mockgoose,在内存包装的mongoose。 我怀疑没有可衡量的连接时间。 我用只testing环境执行我的testing,但没有指定我的urlconfiguration属性。 我的mongoose初始化看起来像这样:

  if (url) { config.logger.info('Attempting Mongoose Connection: ', url); db.connection = connection = mongoose.createConnection(url, { server: { keepAlive: 1, auto_reconnect: true }, user: db.username, pass: db.password }); } else { config.logger.info('No database specified, using Mockgoose in memory database'); config.mockgoose = require('mockgoose')(mongoose); } 

在我的testing中:

  describe('Mockgoose tests', function() { beforeEach(function(done) { config.mockgoose.reset(); // Start with empty database // Other database initialization code here done(); } it('Mockgoose test', function(done) { ... } } 

这使我可以将数据集或单个对象加载到数据库中。 由于mockgoose是在记忆中,它非常快。 缺点是不是所有的mongoose操作都支持mockgoose。 我遇到了结合$或$ elemMatch的查询问题。

由于Mongoosecaching查询,直到连接可用,下面的设置应该足够了:

 describe('test', function () { before(mongoose.connect.bind(mongoose, connectionString)); // do your tests... ); 

但是从错误信息中我可以看出,看起来你没有初始化你的模型。 什么是api.js:63:5的实际代码api.js:63:5