node.bcrypt.js
node.bcrypt.js copied to clipboard
bcrypt.compare always return false when executed in test stage
I wrote a function to authenticate users and in development and production stage work fine. Then, i wrote a test using Jest v27.5.1 for that function and when i run the test, it always will return me "Wrong password" in the first test, where it should return the authToken.
Auth function: `
export const authentication = async (email: string, password: string) => {
try {
// Retrieving data from DB using "sequelize"
const authData = await Customer.findOne({
attributes: ['id', 'password'],
where: { email: email },
raw: true
});
if (!authData)
throw new Error('401|ALPHA-0010|Wrong credentials.');
// In authData['password'] there is the hash of password
const passwordCompare = await bcrypt.compare(password, authData['password']);
if (!passwordCompare)
throw new Error('401|ALPHA-0010|Wrong password.');
return true;
}
catch (error: any) {
console.error(error);
return false;
}
};
`
I was expecting that the first test passes because i pass as arguments a user that exists in my MySQL DB. I'm using Node 17.6.0 on Windows 11.
Test: `
describe('Authentication', () => {
const credentials = {
ok: {
email: '[email protected]',
password: 'Test98@'
},
wrong: {
email: '[email protected]',
password: 'WrongTest98@'
}
};
test('It should return true for successful authentication.', async () => {
const result= await authentication(credentials.ok.email, credentials.ok.password);
expect(result).toBe(true);
});
test('It should return false for worng credentials.', async () => {
const result= await authentication(credentials.wrong.email, credentials.wrong.password);
expect(result).toBe(false);
});
});
`