Nest.js Tutorial

Writing unit tests

Marcin Wanago
JavaScriptNestJSTypeScript

Testing our application can increase our confidence when it comes to creating a fully-functional API. In this article, we look into how we can test our application by writing unit tests. We do so by using some of the utilities built into NestJS, as well as the Jest library.

If you would like to get to know Jest better first, check out the first part of the JavaScript testing tutorial.

Testing NestJS with unit tests

The job of a unit test is to verify an individual piece of code. A tested unit can be a module, a class, or a function. Each of our tests should be isolated and independent of each other. By writing unit tests, we can make sure that individual parts of our application work as expected.

Let’s write some tests for the  AuthenticationService.

src/authentication/tests/authentication.service.spec.ts
1import { AuthenticationService } from '../authentication.service';
2import { UsersService } from '../../users/users.service';
3import { Repository } from 'typeorm';
4import User from '../../users/user.entity';
5import { JwtService } from '@nestjs/jwt';
6import { ConfigService } from '@nestjs/config';
7 
8describe('The AuthenticationService', () => {
9  const authenticationService = new AuthenticationService(
10    new UsersService(
11      new Repository<User>()
12    ),
13    new JwtService({
14      secretOrPrivateKey: 'Secret key'
15    }),
16    new ConfigService()
17  );
18  describe('when creating a cookie', () => {
19    it('should return a string', () => {
20      const userId = 1;
21      expect(
22        typeof authenticationService.getCookieWithJwtToken(userId)
23      ).toEqual('string')
24    })
25  })
26});
PASS src/authentication/tests/authentication.service.spec.ts The AuthenticationService when creating a cookie ✓ should return a string (12ms)

When we execute  npm run test, Jest looks for files ending with  .spec.ts and executes them.

We can improve the above code. Each of our tests needs to be independent, and we need to ensure that. If we add more tests in the above file, all of them will use the same instance of the  AuthenticationService. It breaks the rule of all tests being independent.

To deal with it, we can use the  beforeEach that runs before every test.

src/authentication/tests/authentication.service.spec.ts
1import { AuthenticationService } from '../authentication.service';
2import { UsersService } from '../../users/users.service';
3import { Repository } from 'typeorm';
4import User from '../../users/user.entity';
5import { JwtService } from '@nestjs/jwt';
6import { ConfigService } from '@nestjs/config';
7 
8describe('The AuthenticationService', () => {
9  let authenticationService: AuthenticationService;
10  beforeEach(() => {
11    authenticationService = new AuthenticationService(
12      new UsersService(
13        new Repository<User>()
14      ),
15      new JwtService({
16        secretOrPrivateKey: 'Secret key'
17      }),
18      new ConfigService()
19    );
20  })
21  describe('when creating a cookie', () => {
22    it('should return a string', () => {
23      const userId = 1;
24      expect(
25        typeof authenticationService.getCookieWithJwtToken(userId)
26      ).toEqual('string')
27    })
28  })
29});

Now, we are sure that every test in the  authentication.service.spec.ts file gets a brand new instance of the  AuthenticationService.

Unfortunately, the above code does not look very elegant. Because the constructor of the  AuthenticationService expects some dependencies, we provided them manually so far.

Creating testing modules

Fortunately, NestJS provides us with built-in utilities to deal with the above issue.

1npm install @nestjs/testing

By using  Test.createTestingModule().compile() we can create a module with its dependencies resolved.

src/authentication/tests/authentication.service.spec.ts
1import { AuthenticationService } from '../authentication.service';
2import { Test } from '@nestjs/testing';
3import { UsersModule } from '../../users/users.module';
4import { ConfigModule, ConfigService } from '@nestjs/config';
5import { JwtModule } from '@nestjs/jwt';
6import { DatabaseModule } from '../../database/database.module';
7import * as Joi from '@hapi/joi';
8 
9describe('The AuthenticationService', () => {
10  let authenticationService: AuthenticationService;
11  beforeEach(async () => {
12    const module = await Test.createTestingModule({
13      imports: [
14        UsersModule,
15        ConfigModule.forRoot({
16          validationSchema: Joi.object({
17            POSTGRES_HOST: Joi.string().required(),
18            POSTGRES_PORT: Joi.number().required(),
19            POSTGRES_USER: Joi.string().required(),
20            POSTGRES_PASSWORD: Joi.string().required(),
21            POSTGRES_DB: Joi.string().required(),
22            JWT_SECRET: Joi.string().required(),
23            JWT_EXPIRATION_TIME: Joi.string().required(),
24            PORT: Joi.number(),
25          })
26        }),
27        DatabaseModule,
28        JwtModule.registerAsync({
29          imports: [ConfigModule],
30          inject: [ConfigService],
31          useFactory: async (configService: ConfigService) => ({
32            secret: configService.get('JWT_SECRET'),
33            signOptions: {
34              expiresIn: `${configService.get('JWT_EXPIRATION_TIME')}s`,
35            },
36          }),
37        }),
38      ],
39      providers: [
40        AuthenticationService
41      ],
42    }).compile();
43    authenticationService = await module.get<AuthenticationService>(AuthenticationService);
44  })
45  describe('when creating a cookie', () => {
46    it('should return a string', () => {
47      const userId = 1;
48      expect(
49        typeof authenticationService.getCookieWithJwtToken(userId)
50      ).toEqual('string')
51    })
52  })
53});

There are quite a few issues with the above code still. Let’s deal with them one by one.

Mocking the database connection

The biggest issue above is that we use the  DatabaseModule which means connecting to the real database. When doing unit tests, we want to avoid it.

After removing the  DatabaseModule from our imports we can see an error:

Error: Nest can’t resolve dependencies of the UserRepository (?). Please make sure that the argument Connection at index [0] is available in the TypeOrmModule context.

To work around it, we need to provide a mocked User repository. To do so, we need to use the  getRepositoryToken from  '@nestjs/typeorm.

1import User from '../../users/user.entity';
1providers: [
2  AuthenticationService,
3  {
4    provide: getRepositoryToken(User),
5    useValue: {},
6  }
7],

Unfortunately, the above error persists. This is because we imported  UsersModule that contains TypeOrmModule.forFeature([User]). We should avoid importing our modules when writing unit tests because we don’t want to test integration between classes just yet. We need to add  UsersService to our providers instead.

src/authentication/tests/authentication.service.spec.ts
1import { AuthenticationService } from '../authentication.service';
2import { Test } from '@nestjs/testing';
3import { ConfigModule } from '@nestjs/config';
4import { JwtModule } from '@nestjs/jwt';
5import { getRepositoryToken } from '@nestjs/typeorm';
6import User from '../../users/user.entity';
7import { UsersService } from '../../users/users.service';
8 
9describe('The AuthenticationService', () => {
10  let authenticationService: AuthenticationService;
11  beforeEach(async () => {
12    const module = await Test.createTestingModule({
13      imports: [
14        ConfigModule.forRoot({
15          // ...
16        }),
17        JwtModule.registerAsync({
18          // ...
19        }),
20      ],
21      providers: [
22        UsersService,
23        AuthenticationService,
24        {
25          provide: getRepositoryToken(User),
26          useValue: {},
27        }
28      ],
29    }).compile();
30    authenticationService = await module.get<AuthenticationService>(AuthenticationService);
31  })
32  describe('when creating a cookie', () => {
33    it('should return a string', () => {
34      const userId = 1;
35      expect(
36        typeof authenticationService.getCookieWithJwtToken(userId)
37      ).toEqual('string')
38    })
39  })
40});

The object we put into  useValue above is our mocked repository. We add some methods to it later below.

Mocking ConfigService and JwtService

Since we want to avoid using modules, we also can replace ConfigModule and JwtModule with mocks. To be more precise, we need to provide mocked  ConfigService and  JwtService.

A clean approach to that would be to create separate files for the above mocks.

src/utils/mocks/config.service.ts
1const mockedConfigService = {
2  get(key: string) {
3    switch (key) {
4      case 'JWT_EXPIRATION_TIME':
5        return '3600'
6    }
7  }
8}
src/utils/mocks/jwt.service.ts
1const mockedJwtService = {
2  sign: () => ''
3}

When we use the above, our test now looks like that:

src/utils/mocks/config.service.ts
1import { AuthenticationService } from '../authentication.service';
2import { Test } from '@nestjs/testing';
3import { ConfigService } from '@nestjs/config';
4import { JwtService } from '@nestjs/jwt';
5import { getRepositoryToken } from '@nestjs/typeorm';
6import User from '../../users/user.entity';
7import { UsersService } from '../../users/users.service';
8import mockedJwtService from '../../utils/mocks/jwt.service';
9import mockedConfigService from '../../utils/mocks/config.service';
10 
11describe('The AuthenticationService', () => {
12  let authenticationService: AuthenticationService;
13  beforeEach(async () => {
14    const module = await Test.createTestingModule({
15      providers: [
16        UsersService,
17        AuthenticationService,
18        {
19          provide: ConfigService,
20          useValue: mockedConfigService
21        },
22        {
23          provide: JwtService,
24          useValue: mockedJwtService
25        },
26        {
27          provide: getRepositoryToken(User),
28          useValue: {}
29        }
30      ],
31    })
32      .compile();
33    authenticationService = await module.get(AuthenticationService);
34  })
35  describe('when creating a cookie', () => {
36    it('should return a string', () => {
37      const userId = 1;
38      expect(
39        typeof authenticationService.getCookieWithJwtToken(userId)
40      ).toEqual('string')
41    })
42  })
43});

Changing the mock per test

We do not always want to mock something the same way in each test. To change our implementation between tests, we can use  jest.Mock.

src/users/tests/users.service.spec.ts
1import { Test } from '@nestjs/testing';
2import { getRepositoryToken } from '@nestjs/typeorm';
3import User from '../../users/user.entity';
4import { UsersService } from '../../users/users.service';
5 
6describe('The UsersService', () => {
7  let usersService: UsersService;
8  let findOne: jest.Mock;
9  beforeEach(async () => {
10    findOne = jest.fn();
11    const module = await Test.createTestingModule({
12      providers: [
13        UsersService,
14        {
15          provide: getRepositoryToken(User),
16          useValue: {
17            findOne
18          }
19        }
20      ],
21    })
22      .compile();
23    usersService = await module.get(UsersService);
24  })
25  describe('when getting a user by email', () => {
26    describe('and the user is matched', () => {
27      let user: User;
28      beforeEach(() => {
29        user = new User();
30        findOne.mockReturnValue(Promise.resolve(user));
31      })
32      it('should return the user', async () => {
33        const fetchedUser = await usersService.getByEmail('test@test.com');
34        expect(fetchedUser).toEqual(user);
35      })
36    })
37    describe('and the user is not matched', () => {
38      beforeEach(() => {
39        findOne.mockReturnValue(undefined);
40      })
41      it('should throw an error', async () => {
42        await expect(usersService.getByEmail('test@test.com')).rejects.toThrow();
43      })
44    })
45  })
46});

Summary

In this article, we’ve looked into how to write unit tests in NestJS. To do so, we’ve used the Jest library that comes bundled with NestJS. We’ve also used some of the built-in utilities to mock various services and modules properly. One of the most important ones was mocking the database connection so that we can keep our tests isolated.