I am struggling to make bcrypt.compare() function properly, as it consistently returns false instead of true

Issue:

I am facing a challenge with the

bcrypt.compare(plainText, hashedPassword)
function not returning true even when the plain text password matches the one used to create the hashed password during testing.

Situation:

  • In my project, I am using Mongodb, Express, NodeJS, Jest, and Supertest.
  • Although I have not tested it in Postman yet, I am focusing on improving my skills with Jest first.
  • The user created in the beforeEach function in user.test.ts exists in the database, and the hashed password stored in the database corresponds to the one logged in the controller.ts file.
  • I did manage to pass the test once, but upon removing some console.logs that were used for debugging, the error resurfaced.

Error Encountered:

FAIL  src/components/users/users.test.ts (6.73 s)
  User registration
    ✓ Should create a new user (1985 ms)
    ✓ Should return 400 if user exists (152 ms)
  User login
    ✕ Should login an existing user with valid credentials and return accessToken (215 ms)

  ● User login › Should login an existing user with valid credentials and return accessToken

    expected 200 "OK", got 400 "Bad Request"

      63 |             .post('/user/login')
      64 |             .send(existingUserLogin)
    > 65 |             .expect(200);
         |              ^
...

Code Snippets:

users.test.ts

...

controller.ts:

...

model.ts

...

Actions Taken So Far:

  • Tried switching the arguments of bcrypt.compare from
    bcrypt.compare(plainText, hashedPassword)
    to
    bcrypt.compare(hashedPassword, plainText)
  • Rebuilt with tsc
  • Used a different password than the one mentioned above
  • Ran npm install again
  • Restarted VScode
  • Attempted
    bcrypt.compare(password.trim(), hashedPassword.trim())

It seems like I may be overlooking a simple detail. Appreciate any assistance provided!

Answer №1

Upon investigation, I discovered that in the beforeEach function within users.test.ts, the password hashing process was inadvertently altering the password of the existingUser. This resulted in the third test failing as it attempted to hash an already hashed password instead of the expected "1234567aA".

To resolve this issue, I made the following adjustments:

beforeEach(async () => {
    await User.deleteMany();
    //created a new variable to prevent the existingUser object from being altered
    const newUser = {...existingUser}
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(existingUser.password, salt);
    newUser.password = hashedPassword;
    await User.create(newUser);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting a default value for the dropdown in Angular is essential for ensuring a smooth

<select [(ngModel)]="detail.State" (ngModelChange) ="onStateChange()" class="form-control"> <option [ngValue]="null" disabled selected>Select State</option> <option * ...

A guide on retrieving bytecode from a specific PDF using Angular

Can anyone help me with extracting the bytecode from a selected PDF file to save it in my database? I keep encountering an error stating that my byte is undefined. Could someone please review my code and identify what might be causing this issue? I attemp ...

The error message in monodb.js at line 2: "require is not defined" indicates an issue with the 'require' statement not being

const { MongoClient } = require("mongodb") const url='mongodb://localhost:27017' const client=new MongoClient(url); async function fetchData(){ let result=await client.connect(); let db=result.db("first& ...

What strategies can I implement to enhance the efficiency of my MongoDB Upsert operation?

We recently made the decision to transition our database from SQL to noSQL, and I have some questions regarding best practices and potential improvements for my current implementation. Currently, I am using SQL for upserting player data after a game. ...

The Express Module within Node.js allows for the exporting of functions or objects

When we use express in node, we often write app = express() which indicates that the express module exports only a function, such as module.exports=function(){}. However, when we want to use static files, we typically do something like app.use(express.st ...

Using Angular to automatically update the user interface by reflecting changes made in the child component back to the parent component

Within Angular 5, I am utilizing an *IF-else statement to determine if the authorization value is true. If it is true, then template 2 should be rendered; if false, then template 1 should be rendered. Below is the code snippet: <div *ngIf="authorized; ...

There is no matching signature for Type when using withStyles

Struggling to convert my React App to typescript, I keep encountering the error below and cannot decipher its meaning. The app functions perfectly in plain JS. My package version is material-ui@next TS2345: Argument of type 'typeof ApplicationMenu&a ...

Is it feasible to utilize just one attribute from an external Typescript interface?

Currently, I've incorporated semantic-ui-react into my React project, which provides Typescript typings. Let's take a look at an illustrative type file they offer: Flag.d.ts. import * as React from 'react'; export interface FlagProps ...

There are no specified operations outlined in the Node.js Express documentation

swagger ui https://i.stack.imgur.com/UIavC.png I've been struggling to resolve this issue where the /swagger endpoint seems to only partially read the swagger.json file. Despite configuring everything correctly, no errors are appearing. It simply dis ...

Exploring Pan Gestures in Ionic 3

Looking for information on Pan events in Ionic 3 - not sure if they are related to Cordova or Angular 4? <div class="swipper" #swipper (panleft)="swipe( $event)" (panright)="swipe( $event)" (panend)="swipe( $event) " (panup)="swipe( $event) " (pandown) ...

Tips for fixing connection issues when trying to connect to MongoDB on AWS Cloud9

I've been following a tutorial from 'Web Dev Simplified' using the AWS-Cloud9 Ubuntu environment and everything was going smoothly until I encountered an issue while trying to connect to MongoDB. The database appeared to install correctly us ...

Ways to determine if a date matches today's date within a component template

I am currently displaying a list of news articles on the webpage and I want to show the word "Today" if the news article's date is equal to today's date. Otherwise, I want to display the full date on the page. Is there a way to compare the news.D ...

When using Angular 2, an error may occur where you receive a message stating that you cannot read the property 'length' of undefined while attempting to call

When creating a component (let's call it A) with the @input decorator to retrieve values from the selector, keep in mind that this component will generate text fields based on the input values specified in the selector. Component A is then utilized in ...

Angular JS Cross-Origin POST Request

I have been attempting to execute a post request using AngularJS, but unfortunately, it's not functioning as expected. The issue seems to lie in the fact that the origin URL differs from the server. On one hand, the server operates on a Node Express a ...

What steps should I follow to utilize a JavaScript dependency following an NPM installation?

After successfully installing Fuse.js using npm, I am having trouble using the dependency in my JavaScript code. The website instructions suggest adding the following code to make it work: var books = [{ 'ISBN': 'A', 'title&ap ...

What is the process for designing a mapping type that involves two enums?

I need a solution to connect these two types and create mappings: type MappedEnum<T extends string, A extends string, B extends string> = { [key in T]: {[key in A]: B}; [key in T]: {[key in B]: A}; }; enum Greek { ALPHA = 'A', BET ...

Having issues with asynchronous function; unable to update and upload image

Currently, I am working on a function that involves a page where the user is prompted to upload a profile picture and provide some personal information. Here is what I have managed to implement so far: router.post('/edit/:id', async function(req ...

Issue with throttle function not properly handling the class method call

I am facing a challenge with my code where I am trying to throttle text input, but it seems that calling another method is causing the throttling to not work as expected. import { throttle } from 'lodash'; ... <input type="t ...

A guide to effectively logging data with Node.js and MongoDB using console.log

I am trying to log data from a MongoDB collection, but for some reason it is not working. It should be simple, but it's just frustrating. Below is the code I am using: //this is what i have: var express = require('express'); v ...

Trouble detecting type definitions in Typescript typeRoots

I'm incorporating TypeScript into my project. When I attempt to bring in a package using commonJS const { v4: uuidv4 } = require('uuid'); No errors occur during compilation. However, when I transform it into an ES6 module like this: import ...