Skip to content

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

@TannicArturo98

Description

@TannicArturo98

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);
    });
});

`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions