[英]How to test mongoose pre hook 'save' and bcryptjs
I trying to create unit tests for mongoose model.我试图为 mongoose model 创建单元测试。 I do not think how to test bcryptjs.hash in my schema.我不认为如何在我的架构中测试bcryptjs.hash 。
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但我的错误是: TypeError: Attempted to wrap undefined property hash as function
You could mock the bcrypt doing that你可以模拟 bcrypt 这样做
import bcryptjs from 'bcryptjs'
sinon.stub(bcryptjs, 'hash').callsFake(() => Promise.resolve('hash'))
and your test could use你的测试可以使用
const bcryptjsSpy = sinon.spy(bcryptjs, 'hash')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.