使用'预先保存'的mongoose钩子似乎会导致我的单元测试超时(超过2000毫秒)。
当我注释掉预保存挂钩时,单元测试工作正常......但是当包含预保存挂钩时,测试会超时并且不会返回任何特定的错误消息。
关于什么可能出错的任何想法?
模型(User.js)
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var Schema = mongoose.Schema;
var userSchema = new Schema({
"auth": {
"local": {
"email": String,
"password": String,
}
},
"userProfile" : {
"firstname" : {"_default": String},
"lastname" : {"_default": String},
"username": String,
"email" : String,
}
});
userSchema.method('genHash',function(password){
return bcrypt.hashSync(password, bcrypt.genSaltSync(9));
});
userSchema.method('isValidPassword', function(candidatePassword){
return bcrypt.compareSync(candidatePassword, this.auth.local.password);
});
// PROBLEM CODE
// userSchema.pre('save', function(next) {
// var user = this;
// if(!user.isModified('auth.local.password')) return next();
// // watch this, I have seperated out this function.
// user.auth.local.password = user.genHash(user.auth.local.password);
// });
module.exports = mongoose.model('User', userSchema);
单元测试(摩卡)
var chai = require('chai');
var expect = chai.expect;
var mongoose = require('mongoose');
var User = require('../../models/user');
var config = require('../../config/env');
chai.config.includeStack = true;
// User model
var mochUser = new User({
auth: {
local: {
email: "smith@gmail.net",
password: "test"
}
},
userProfile: {
firstname: {
_default: "Nathan"
},
lastname: {
_default: "Trent"
},
email: "trent@hotmail.com"
}
});
before(function() {
if(mongoose.connection.db) return;
mongoose.connect(config.db.test);
});
describe('User Model', function() {
// this.timeout(5000);
it("Should save object",function (done){
mochUser.save(function(error) {
console.log("Saving");
expect(error).to.not.exist;
console.log("No issue.");
done();
});
});
});