DEV Community

Cover image for Testing in NestJS: A Comprehensive Guide
Chafroud Tarek
Chafroud Tarek

Posted on

Testing in NestJS: A Comprehensive Guide

In this blog, we'll explore testing authentication in NestJS. We'll cover strategies, tools, and best practices to ensure robust authentication mechanisms. Topics include unit testing and mocking dependencies. By the end, you'll gain a comprehensive understanding of how to effectively test authentication in your NestJS applications.

Below, you will find the default content of the file, which serves as a starting point for testing. If you are already familiar with tests, you'll quickly grasp its structure and purpose. However, if you're new to testing, don't worry—I'll provide detailed explanations with comments for each part to help you understand it better.
Image description

Now we will test the resolver/controller (are the same) :

▪️ the first case is the signup

Image description

1️⃣ : On the providers, you need to add all the services you use. In my case, it would be like this

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        AuthResolver,
        AuthService,
        PasswordService,
        JwtService,
        PrismaService,
        ConfigService,
      ],
    }).compile();

    resolver = module.get<AuthResolver>(AuthResolver);
    authService = module.get<AuthService>(AuthService);
  });
Enter fullscreen mode Exit fullscreen mode

⚠️: I added the authService because I will use it later to spy actions performed by my resolver.

2️⃣ : add the test case :

Image description
3️⃣ : mock the input data and the tokens

   const data: SignupInput = {
      email: 'test@example.com',
      roleId: 'admin',
      password: 'password',
      username: 'testName',
    };
 const tokens = {
    accessToken: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmb29',
    refreshToken: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmb29',
  };
Enter fullscreen mode Exit fullscreen mode

4️⃣ : we need to spy the createUser method that exist on our authService by using this line :

//spyOn: allows you to create a spy on a particular method of an object or class
const createUserSpy = jest.spyOn(authService, 'createUser');
// mock the resolved value of the createUser method 
 createUserSpy.mockResolvedValue(tokens);
Enter fullscreen mode Exit fullscreen mode

5️⃣ : mock the cookies

 const cookieMock = jest.fn();
 response.cookie = cookieMock;
Enter fullscreen mode Exit fullscreen mode

6️⃣ : and now it's time to calling the signup method of the resolver object, which corresponds to the signup resolver function

 // It will simulate the signup process using our mock data
  const result = await resolver.signup(data, response);
Enter fullscreen mode Exit fullscreen mode

7️⃣ : and the last steo is to set the expectations :

expect(createUserSpy).toHaveBeenCalledWith(data, response);
    expect(cookieMock).toHaveBeenCalledWith(
      'refreshToken',
      tokens.refreshToken
    );
    expect(result).toEqual(tokens);
Enter fullscreen mode Exit fullscreen mode

The final result : 👇

Image description

With the same way we can test the others :

▪️ Login:

Image description

▪️ RefreshToken:

Image description

▪️ decodeUser:

Image description

Finally,
I don't test all cases to keep the blog lightweight. Feel free to message me for more details or if you have any questions. I hope you find it enjoyable. See you in another blog 👋.

Top comments (0)