kelektiv / node.bcrypt.js

bcrypt for NodeJs
MIT License
7.43k stars 510 forks source link

bcrypt.compare always return false when executed in test stage #923

Open TannicArturo98 opened 2 years ago

TannicArturo98 commented 2 years ago

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: 'seed@test.com',
            password: 'Test98@'
        },
        wrong: {
            email: 'wrong@test.com',
            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);
    });
});

`