首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何测试猫鼬预钩“保存”和bcryptjs

如何测试猫鼬预钩“保存”和bcryptjs
EN

Stack Overflow用户
提问于 2021-04-09 15:08:50
回答 1查看 208关注 0票数 0

我试图为猫鼬模型创建单元测试。我不认为如何在我的模式中测试bcryptjs.hash

这是我的用户模式:

代码语言:javascript
复制
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);

这是我的考验:

代码语言:javascript
复制
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:试图将未定义的属性哈希包装为函数

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-09 17:07:27

你可以嘲笑地下墓穴

代码语言:javascript
复制
import bcryptjs from 'bcryptjs'

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

你的测试可以用

代码语言:javascript
复制
const bcryptjsSpy = sinon.spy(bcryptjs, 'hash')
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67023679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档