如何测试 mongoose pre hook 'save' 和 bcryptjs

How to test mongoose pre hook 'save' and bcryptjs

我正在尝试为猫鼬模型创建单元测试。我不认为如何在我的架构中测试 bcryptjs.hash
这是我的用户架构:

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

这是我的测试:

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

但我的错误是:TypeError: Attempted to wrap undefined 属性 hash as function

你可以模拟 bcrypt 这样做

import bcryptjs from 'bcryptjs'

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

并且您的测试可以使用

const bcryptjsSpy = sinon.spy(bcryptjs, 'hash')