Testing in NestJS: A Comprehensive Guide
Tags: typescript, node, learning, webdev
Published: 2023-07-06 13:43:44

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5go22zackfgdx4m48kzo.png)

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

 ▪️ the first case is the signup 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/athv55as7exzn838b0uh.png)



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);
  });
```
⚠️: I added the authService because I will use it later to spy actions performed by my resolver.

2️⃣ : add the test case :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/49qpt6klpsl4mak61naq.png)
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',
  };
```

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);
```
5️⃣ : mock the cookies 

```
 const cookieMock = jest.fn();
 response.cookie = cookieMock;
```
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);
```
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);
```

**The final result : 👇**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m785zbwfjg319gdhbj0x.png)

**With the same way we can test the others :**

▪️ Login: 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pqnfeqj78hkw2k76je95.png)

▪️ RefreshToken: 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ekrpn9j8x2wja5kskhdv.png)

▪️ decodeUser: 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mwci70seskzyb3ggux8b.png)

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