2015-02-12 59 views
1

我有一个使用Supertest的使用MongoDB的快速API的摩卡测试。 MongoDB是跑步,但我目前有Supertest要求和使用Express API而不是单独启动它(我更喜欢这种方法):在API初始化之前持有Supertest

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

当测试运行时,它失败:

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

我怀疑supertest是在MongoDB连接建立之前在我的API上运行测试。在我的API完全初始化之前,什么才能让它延续下去?

我想如果我在启动express之后通过Grunt进行测试,它会很好,但是由于Supertest可以代表我开始表达,所以我希望能够以这种方式开始。

回答

1

你可以做到以下几点:

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

我使用Mockgoose,一个在内存包装的猫鼬运行我的测试。我怀疑没有可衡量的连接时间。我使用仅测试环境执行测试,但未指定我的url配置属性。我的猫鼬初始化看起来是这样的:

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

在我的测试:

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在内存中,它非常快。缺点是不是所有的猫鼬操作都支持mockgoose。我遇到了结合$或$ elemMatch的查询问题。

0

由于猫鼬缓冲查询,直到连接可用,下面的设置应该足够:

describe('test', function() { 
    before(mongoose.connect.bind(mongoose, connectionString)); 

    // do your tests... 
); 

但是,从我可以通过错误消息告诉,它看起来像你无法初始化您的模型。什么是api.js:63:5的实际代码?

相关问题