mongoose模式unit testing失败与前保存挂钩

使用“预保存”mongoose钩似乎会导致我的unit testing超时(超过2000毫秒的错误)。

当我注释掉预保存钩子时,unit testing工作正常……但是当包含pre-save-hook时,testing超时并且不返回任何特定的错误消息。

任何想法可能是错的?

模型(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); 

unit testing(摩卡)

 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(); }); }); });