我来晚了,但我找到了在express应用中设置mocha测试套件的最佳方法是让我的app.js或server.js文件导出app对象,就像这样:
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');
mongoose.connect(config.db);
middleware(app);
routes(app);
app.listen(app.get('port'));
console.log('Express server listening on port ' + app.get('port'));
exports = module.exports = app;
确保您的配置文件中设置了不同的环境,如开发、测试、生产:
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: {
}
}
然后在你的测试文件中,你可以继续引入你的应用程序,它将连接到正确的数据库和正确的端口:
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');
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):
"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
启动应用程序。
希望这有所帮助!
附注:我从这个令人惊叹的示例中学到了大部分内容:
https://github.com/madhums/node-express-mongoose-demo