Skip to content
Advertisement

How to test mongoose pre hook ‘save’ and bcryptjs

I trying to create unit tests for mongoose model. I do not think how to test bcryptjs.hash in my schema.
This is my User Schema:

const userSchema = new mongoose.Schema<IUser>({
  name: {
    type: String,
    require: true,
    minLength: 2
  },
  email: {
    type: String,
    require: true,
    unique: true,
    validate: {
      validator: (email: string) => {
        return validator.isEmail(email);
      },
      message: (props: IProps) => `${props.value} email is not valid!`
    }
  },
  password: {
    type: String,
    require: true,
    minLength: 3
  }
});

userSchema.pre('save', async function (next) {
  const user = this;
  const hash = await bcryptjs.hash(user.password, 10);
  user.password = hash;
  next();
});

userSchema.methods.isValidPassword = async function(password: string): Promise<boolean> {
  const user = this;
  const compare = await bcryptjs.compare(password, user.password);
  return compare;
}

export const User = mongoose.model('user', userSchema);

This is my test:

it('Password should be hashing', async () => {
    sinon.stub(User, 'create').callsFake(() => {return 42});

    const spy = sinon.spy(bcryptjs, 'hash');
    await User.create({name: arrayOfUsers[0].name, email: arrayOfUsers[0].email, password: arrayOfUsers[0].password});

    expect(spy.called).to.equal(true);
  })

But I have error is: TypeError: Attempted to wrap undefined property hash as function

Advertisement

Answer

You could mock the bcrypt doing that

import bcryptjs from 'bcryptjs'

sinon.stub(bcryptjs, 'hash').callsFake(() => Promise.resolve('hash'))

and your test could use

const bcryptjsSpy = sinon.spy(bcryptjs, 'hash')
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement