我迟到了,但我发现为快速应用程序设置 mocha 测试套件的最佳方法是让我的 app.js 或 server.js 文件导出应用程序对象,如下所示:
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;
确保您的配置文件具有不同的环境,例如开发、测试、生产设置:
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');
// 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):
"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
.
希望能帮助到你!ps:我从这个惊人的例子中学到的大部分东西:
https ://github.com/madhums/node-express-mongoose-demo