lundi 27 juillet 2015

Mongoose Schema Unit Test fails with Pre Save hook

Using a 'pre-save' mongoose hook seems to cause my unit tests to time out (2000ms exceeded error).

When I comment out the pre-save hook, the unit test works fine... but when the pre-save-hook is included, the test times out and doesn't return any specific error message.

Any ideas on what could be wrong?

Model (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 Test (Mocha)

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

Aucun commentaire:

Enregistrer un commentaire