我在某些控制器单元测试中使用mockgoose来模拟数据库。运行我的测试套件后,我可以在我的数据库中的测试套件中找到具有凭据的用户。我觉得这与我在app.js中连接的事实有关,但我迷失了。
此处的相关代码:
app.js:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var mongoose = require('mongoose');
var db;
mongoose.connect('mongodb://****:****@ds053438.mlab.com:53438/express-crud');
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
require('./router')(app);
路由器/控制器:
var User = require('../../models/user');
var routes = function(app) {
var baseUrl = app.get('baseUrl') + '/users';
/* POST new user */
app.post(baseUrl + '/', function (req, res, next) {
var user = new User();
// FOR THE LOVE OF GOD HASH PASSWORD IDIOT
user.password = req.body.password;
user.username = req.body.username;
user.admin = false;
User.create(user, function (err, createdUser) {
if (err) {
return next(err);
}
res.status(200).send({
message: 'success',
username: createdUser.username,
success: true
});
});
});
}
module.exports = routes;
模型:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: {
type: String,
required: true,
minlength: 4,
trim: true
},
// hash it nerd.
password: {
type: String,
required: true,
minlength: 12,
trim: true
},
admin: {
type: Boolean,
required: true
}
});
module.exports = mongoose.model('User', UserSchema);
测试:
var expect = require('chai').expect;
var request = require('supertest');
var mongoose = require('mongoose');
var mockgoose = require('mockgoose');
mockgoose(mongoose);
var app = require('../../app.js');
var baseUrl = app.get('baseUrl');
describe('CONTROLLERS', function() {
describe('/users/', function () {
describe('POST', function () {
it('responds with 200 for valid payload', function (done) {
request(app)
.post(baseUrl + '/users')
.set('Accept', 'application/json')
.send({
'username': 'testUserWithMockgoose',
'password': 'testPasswordThatsLongEnough'
})
.expect(200)
.end(function (err, res) {
if (err) {
return done(err);
}
done();
})
})
});
});
});
这不是我的完整代码,但我试图将其修剪而不会丢失任何相关信息。谢谢!