我正在使用这个依赖项:https://www.npmjs.com/package/bcrypt。
我正在尝试测试此功能:
VolunteerSchema.statics.findByCredentials = function (email, password) {
var Volunteer = this
var foundVolunteer
return Volunteer.findOne({email}).then((volunteer) => {
if (volunteer) {
foundVolunteer = volunteer
return bcrypt.compareSync(password, volunteer.password)
} else {
return Promise.reject({error: "Email not found"})
}
}).then((response) => {
if (response) {
console.log("Sending found vol", foundVolunteer)
return Promise.resolve(foundVolunteer)
} else {
return Promise.reject({error: "Incorrect password"})
}
})
};
开玩笑地进行以下测试:
test('Valid credentials', async () => {
var volunteerValid = new Volunteer({
name : 'Test Time',
phone: '1111111111',
password: 'test password',
email : 'abc@xyz.com'
})
await volunteerValid.save()
await expect(Volunteer.findByCredentials('abc@xyz.com', 'test password')).resolve.toEqual(volunteerValid)
})
我遇到的问题是,即使我在测试中使用了 async-await,该函数也会在测试执行后返回志愿者。
此外,对于此行代码:
console.log("Sending found vol", foundVolunteer)
开玩笑给我错误:测试完成后无法记录。您是否忘记在测试中等待异步内容?
你能帮我弄清楚为什么会这样吗?
您将同步和异步模式混合到您的函数( findByCredentials ( 中,您可以将 findByCredentials 声明为异步并在异步调用时使用 await
VolunteerSchema.statics.findByCredentials = async function (email, password) {
var Volunteer = this
// TODO consider to put a try catch when you call findOne method
let volunteer = await Volunteer.findOne({email})
if(!volunteer){
throw new Error({error: "Email not found"})
}
if (bcrypt.compareSync(password, volunteer.password)) {
console.log("Sending found vol", volunteer)
return volunteer
} else {
throw new Error({error: "Incorrect password"})
}
};