确保 Express App 在每次 Mocha 测试之前运行 [英] Ensuring Express App is running before each Mocha Test

查看:23
本文介绍了确保 Express App 在每次 Mocha 测试之前运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ExpressJS、NodeJS、Mongoose 和 Mocha 开发 REST API.

I am working on developing a REST API using ExpressJS, NodeJS, Mongoose and Mocha.

问题是我有一个 app.coffee 文件,它负责设置 ExpressJS 并连接到 Mongoose.我设置的方式是先连接 Mongoose,如果连接成功,则启动 ExpressJS 应用程序.

The thing is that I have an app.coffee file, thats responsible for setting up ExpressJS and connecting to Mongoose. The way I have set this up is that Mongoose is connected first and if that gets through, then, the ExpressJS App is started.

问题是,在设置 Mocha 时,我需要确保 app.coffee 中存在的 ExpressJS App 完全启动成功,包括在执行任何测试用例之前的所有异步代码.

The issue is that when setting up Mocha, I need to make sure that ExpressJS App existing in app.coffee is completely started successfully including all asynchronous code before any testcase is executed.

为此,我创建了一个 test_helper.coffee 并将以下代码放入其中,但是,即使 app.coffee 中的代码尚未完全执行,测试用例也会开始执行,这实际上是有道理的:

For that, I have created a test_helper.coffee and placed the following code in it, but, the testcases start their execution even if the code in app.coffee hasn't completed its execution completely which actually makes sense:

before (done) ->
  require(__dirname + '/../src/app')
  done()

简而言之,我想确保在执行任何测试用例之前 ExpressJS 应用程序已完全完成其设置.

In a nutshell, I want to make sure that the ExpressJS app has fully completed its setup before any testcase is executed.

我该怎么做?

推荐答案

我迟到了,但我发现为 express 应用设置 mocha 测试套件的最佳方法是制作我的 app.js 或服务器.js 文件导出 app 对象,如下所示:

I am late to the party, but I found the best way to set up my mocha test suite for an express app is to make my app.js or server.js file export the app object, like this:

var mongoose = require('mongoose');
var express = require('express');
require('express-mongoose');

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

var models = require('./app/models');
var middleware = require('./app/middleware');
var routes = require('./app/routes');

var app = express();

app.set('port', process.env.PORT || config.port || 3000);
app.set('views', __dirname + '/app/views');
app.set('view engine', 'jade');

// database
mongoose.connect(config.db);

// middleware
middleware(app);

// Application routes
routes(app);

app.listen(app.get('port'));
console.log('Express server listening on port ' + app.get('port'));

// export app so we can test it
exports = module.exports = app;

确保您的配置文件具有不同的环境,例如开发、测试、生产设置:

make sure your config file has different environments like development, test, production set up:

var path = require('path');
var rootPath = path.normalize(__dirname + '/..');

module.exports = {
  development: {
    db: 'mongodb://localhost/my_dev_db',
    port: 3000
  },
  test: {
    db: 'mongodb://localhost/my_test_db',
    port: 8888
  },
  production: {
    // ...
  }
}

然后在您的测试文件中,您可以继续并要求您的应用程序,该应用程序将连接到正确的数据库和正确的端口:

then in your test files you can go ahead and require your app, which will connect to the right db and on the right port:

var should = require('chai').should();
var request = require('supertest');
var mongoose = require('mongoose');

var app = require('../app');
var agent = request.agent(app);

var User = mongoose.model('User');

    // get users
    describe('GET /api/users', function() {
      it('returns users as JSON', function(done) {
        agent
        .get('/api/users')
        .expect(200)
        .expect('Content-Type', /json/)
        .end(function(err, res) {
          if (err) return done(err);
          res.body.should.have.property('users').and.be.instanceof(Array);
          done();
        });
      });
    });

最后,为了启动整个怪物,你将它包含在你的 package.json 中(确保你的 devDependencies 中有 nodemon 和 mocha):

And finally, to start up the whole monster you include this in your package.json (make sure to have nodemon and mocha in your devDependencies):

"scripts": {
    "start": "NODE_ENV=development ./node_modules/.bin/nodemon app.js",
    "test": "NODE_ENV=test ./node_modules/.bin/mocha --reporter spec test/**.js"
  }

现在您可以使用 npm test 启动测试套件,使用 npm start 启动您的应用.

Now you can start your test suite with npm test and your app with npm start.

希望有帮助!ps:我从这个惊人的例子中学到的大部分东西:https://github.com/madhums/node-express-mongoose-demo

Hope it helps! ps: most of the stuff I learned from looking at this amazing example: https://github.com/madhums/node-express-mongoose-demo

这篇关于确保 Express App 在每次 Mocha 测试之前运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆