【问题标题】:How to test mongoose pre hook 'save' and bcryptjs如何测试猫鼬预钩“保存”和bcryptjs
【发布时间】:2021-07-05 11:39:31
【问题描述】:

我尝试为猫鼬模型创建单元测试。我不认为如何在我的架构中测试 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 property hash as function

【问题讨论】:

    标签: javascript node.js typescript mongoose schema


    【解决方案1】:

    你可以模拟 bcrypt 这样做

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

    你的测试可以使用

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

    【讨论】:

    • 谢谢)我还安装了 chai-http
    猜你喜欢
    • 2018-03-04
    • 2012-08-08
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 2013-08-14
    • 1970-01-01
    • 2012-07-12
    相关资源
    最近更新 更多