【问题标题】:Timeout when running mocha test on mongoose model and express route在猫鼬模型和快速路线上运行摩卡测试时超时
【发布时间】:2013-12-04 12:50:18
【问题描述】:

我在为我的 Mongoose 模型我的 express 应用(路线)编写测试时遇到问题

我有一个非常简单的app.js 文件:

var env = process.env.NODE_ENV || 'development',
    express = require('express'),
    config = require('./config/config')[env],
    http = require('http'),
    mongoose = require('mongoose');

// Bootstrap db connection
mongoose.connect(config.db)

// Bootstrap models
var models_path = __dirname + '/app/model';
fs.readdirSync(models_path).forEach(function(file) {
    if (~file.indexOf('.js')) {
        require(models_path + '/' + file);
    }
});

var app = express();

// express settings
require('./config/express')(app, config);

// Bootstrap routes
require('./config/routes')(app, compact);

if (!module.parent) {
    app.listen(app.get('port'), function() {
        console.log('Server started on port ' + app.get('port'));
    })
}

module.exports = app;

我有一个名为 model 的文件夹,其中包含我的猫鼬模型。

我有一个test 文件夹,带有accountTest.js - 看起来有点像这样:
(这是为了测试我的 Account 模型)

var utils = require('./utils'),
  should = require('chai').should(),
  Account = require('../app/model/account');

describe('Account', function() {
  var currentUser = null;
  var account = null;

  it('has created date set on save', function(done) {
    var account = new Account();

    account.save(function(err) {
      account.created.should.not.be.null;
      done();
    });
  });

utils 取自这里:http://www.scotchmedia.com/tutorials/express/authentication/1/06

如果我把它留在这一次测试中,这很有效。

如果我添加另一个测试来测试我的快速路线,如下所示:

var request = require('supertest'),
    app = require('../../app'),
    should = require('chai').should();

describe('Account controller', function() {

    it('GET /account returns view', function(done) {
        //omitted for brevity
        done();
    });
});

然后我在对我的模型进行测试时遇到超时错误...

影响它的行是app = require('../../app')
如果我删除它,那么就没有超时。

我意识到这可能与 mongoose 连接有关,但不确定如何在测试之间“共享”它?

【问题讨论】:

    标签: node.js express mongoose mocha.js supertest


    【解决方案1】:

    mocha 有一个root Suite:

    You may also pick any file and add "root" level hooks, for example add beforeEach() outside of describe()s then the callback will run before any test-case regardless of the file its in. This is because Mocha has a root Suite with no name.

    使用它来启动您的 Express 服务器一次(我们使用环境变量,以便它在与我们的开发服务器不同的端口上运行):

    before(function () {
      process.env.NODE_ENV = 'test';
      require('../../app.js');
    });
    

    (我们在这里不需要done(),因为require 是同步的。)也就是说,服务器只启动一次,无论有多少不同的测试文件包含这个根级别的before 函数。

    【讨论】:

    • 但我不想/不需要在我的 Mongoose 模型测试中要求 app.js,或者我需要吗?
    • 基本思想是使用 before 语句包裹所有需要该功能的测试,以避免调用它两次。您可能只需要您的 Mongoose 模型,但如果您有其他测试 Express 和 Express 需要您的模型的测试,那么您最好只需要 Express。
    • 如果我只想测试我的模型,我会需要 app.js (express) 吗……这没有意义吗?当然必须是更好的方法
    • 尝试只需要你的模型。
    猜你喜欢
    • 2014-11-22
    • 2013-05-24
    • 2016-12-26
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 2017-06-23
    相关资源
    最近更新 更多