1

I am using https://github.com/mhevery/jasmine-node to test my nodejs server routes. My mongoose model has a working pre function as below

userSchema.pre('save', function(next) {
  var user = this;
  if (!user.isModified('password')) return next();
      bcrypt.genSalt(10, function(err, salt) {
         if (err) return next(err);

             logger.info('Hashing password!!!');

             bcrypt.hash(user.password, salt, null, function(err, hash) {
                  if (err) return next(err);
                  user.password = hash;
                  next();
             });
      });
});

Now I need to write a test case in jasmine that creates a userSchema object and saves it to mongodb to use it further in my test case.

var User = require("../../../../models/User");

            it("{postLogin - invalid}", function(done) {
                var user = new User({email: "test@test.com", password: "a"});

                user.save(function(err) {
                if (err){
                    console.log(err);
                    return next(err);
                }
                console.log('user saved to db: ' +user.email);  
                request.post(invalidLoginParams, function(error, response, body) {
                    expect(response.statusCode).toBe(400);
                    done();
                });              
            });
    },15000);

I run the above test case using jasmine-node and i get the log 'Hashing password!!!' which means it is calling this function. But after this it never returns to my test case. It should print the log 'user saved to db: ' But it is never returning back from .pre('save') function. Any idea where and what am i missing. Could not find any answer on google. Hope to get it here! Thanks

maxboo
  • 118
  • 8
  • It look like you have to call `done` in jasmine when `user.save` have error. – greenlikeorange Jul 29 '15 at 14:47
  • @greenlikeorange Can you elaborate? coz `done()` is called if there is no error. And there is no error in `save`. It just does not come back from save to my testcase. – maxboo Jul 30 '15 at 07:36
  • `done` is need to call anytime when your job is done, if you have error you have to call `return done(error)` instance of `return next(err)`. Then you can know, there is error or not at logs – greenlikeorange Jul 30 '15 at 17:12
  • ok i tried this. Added `done(err)` instead of `return(err)`. It does not throw an error. it is just stuck and does not return from `save` . Nobody has a solution here? – maxboo Jul 31 '15 at 05:55

1 Answers1

2

please make sure to call the callback "done()" properly.

Syed Faizan
  • 901
  • 3
  • 14
  • 28