Search⌘ K
AI Features

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.

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 signUp method throws a ConflictException when an email is already in use.

  • Dealing with unexpected errors: Check how the signUp method responds to unforeseen issues.

  • Successful user registration: Ensure that the signUp function successfully hashes the password and saves the new user to the database.

Test: Handling email conflicts

  • Objective: Ensure the signUp function correctly handles cases where a user tries to sign up with an email already in use.

Key points to test:

  • The function throws a ConflictException when 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:

Adding a console.log statement to verify the error log during testing of email conflict handling

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 ...