Unit Testing for the signUp Method of AuthService
Explore writing unit tests for the signUp method in NestJS AuthService. Understand how to simulate email conflicts, test unexpected error handling, mock bcrypt for password hashing, and verify successful user registration. This lesson helps you ensure robust authentication functionality and reliable test coverage.
We'll cover the following...
In this lesson, we’ll write our first tests for our virtual library. We’ll address the following scenarios:
Handling email conflicts: We ensure the
signUpmethod throws aConflictExceptionwhen an email is already in use.Dealing with unexpected errors: Check how the
signUpmethod responds to unforeseen issues.Successful user registration: Ensure that the
signUpfunction successfully hashes the password and saves the new user to the database.
Test: Handling email conflicts
Objective: Ensure the
signUpfunction correctly handles cases where a user tries to sign up with an email already in use.
Key points to test:
The function throws a
ConflictExceptionwhen an email is already in use.
When a user attempts to sign up with an email already in our virtual library, userRepository.save responds with a unique violation error identified by the code 23505.
Let’s focus on line 32 in auth.service.ts, where we’ll simulate this behavior of userRepository.save. Let’s see how to do that:
Let’s insert a console.log(error) in line 34 in the auth.service.ts file. This will help us verify if the intended error log appears as expected.
Now press the “Run” button to ...