Nest.js Tutorial

Unit tests with PostgreSQL and Kysely

Marcin Wanago
NestJS

Creating tests is essential when trying to build a robust and dependable application. In this article, we clarify the concept of unit tests and demonstrate how to write them for our application that interacts with PostgreSQL and uses the Kysely library.

Explaining unit tests

A unit test ensures that a specific part of our code operates correctly. Using these tests, we can confirm that different sections of our system function properly on their own. Each unit test should be independent and isolated.

When we execute the npm run test command, Jest searches for files following a particular naming pattern. When we use NestJS, it looks for files that end with .spec.ts by default. Another common practice is to use files with the .test.ts extension. You can find this configuration in our package.json file.

package.json
1{
2  // ...
3  "jest": {
4    "testRegex": ".*\\.(spec|test)\\.ts$",
5    // ...
6  }
7}

Let’s start by creating a simple test for our AuthenticationService class.

authentication.service.test.ts
1import { AuthenticationService } from './authentication.service';
2import { JwtService } from '@nestjs/jwt';
3import { ConfigService } from '@nestjs/config';
4import { Pool } from 'pg';
5import { UsersService } from '../users/users.service';
6import { UsersRepository } from '../users/users.repository';
7import { Database } from '../database/database';
8import { PostgresDialect } from 'kysely';
9 
10describe('The AuthenticationService', () => {
11  let authenticationService: AuthenticationService;
12  beforeEach(() => {
13    const configService = new ConfigService();
14 
15    authenticationService = new AuthenticationService(
16      new UsersService(
17        new UsersRepository(
18          new Database({
19            dialect: new PostgresDialect({
20              pool: new Pool({
21                host: configService.get('POSTGRES_HOST'),
22                port: configService.get('POSTGRES_PORT'),
23                user: configService.get('POSTGRES_USER'),
24                password: configService.get('POSTGRES_PASSWORD'),
25                database: configService.get('POSTGRES_DB'),
26              }),
27            }),
28          }),
29        ),
30      ),
31      new JwtService({
32        secretOrPrivateKey: 'Secret key',
33      }),
34      new ConfigService(),
35    );
36  });
37  describe('when calling the getCookieForLogOut method', () => {
38    it('should return a correct string', () => {
39      const result = authenticationService.getCookieForLogOut();
40      expect(result).toBe('Authentication=; HttpOnly; Path=/; Max-Age=0');
41    });
42  });
43});
PASS src/authentication/authentication.service.test.ts The AuthenticationService when calling the getCookieForLogOut method ✓ should return a correct string

In the example above, we’re calling the AuthenticationService constructor manually. While this is one of the possible solutions, we can rely on NestJS test utilities to handle it for us instead. To do that, we need the Test.createTestingModule method from the @nestjs/testing library.

authentication.service.test.ts
1import { AuthenticationService } from './authentication.service';
2import { JwtModule } from '@nestjs/jwt';
3import { ConfigModule, ConfigService } from '@nestjs/config';
4import { DatabaseModule } from '../database/database.module';
5import { UsersModule } from '../users/users.module';
6import { Test } from '@nestjs/testing';
7import { EnvironmentVariables } from '../types/environmentVariables';
8 
9describe('The AuthenticationService', () => {
10  let authenticationService: AuthenticationService;
11  beforeEach(async () => {
12    const module = await Test.createTestingModule({
13      providers: [AuthenticationService],
14      imports: [
15        UsersModule,
16        ConfigModule.forRoot(),
17        JwtModule.register({
18          secretOrPrivateKey: 'Secret key',
19        }),
20        DatabaseModule.forRootAsync({
21          imports: [ConfigModule],
22          inject: [ConfigService],
23          useFactory: (
24            configService: ConfigService<EnvironmentVariables, true>,
25          ) => ({
26            host: configService.get('POSTGRES_HOST'),
27            port: configService.get('POSTGRES_PORT'),
28            user: configService.get('POSTGRES_USER'),
29            password: configService.get('POSTGRES_PASSWORD'),
30            database: configService.get('POSTGRES_DB'),
31          }),
32        }),
33      ],
34    }).compile();
35 
36    authenticationService = await module.get(AuthenticationService);
37  });
38  describe('when calling the getCookieForLogOut method', () => {
39    it('should return a correct string', () => {
40      const result = authenticationService.getCookieForLogOut();
41      expect(result).toBe('Authentication=; HttpOnly; Path=/; Max-Age=0');
42    });
43  });
44});

Above, we create a mock of the entire NestJS runtime. Then, when we execute the compile() method, we set up the module with its dependencies in a manner similar to how the bootstrap function in our main.ts file functions.

Avoiding connecting to the actual database

The above code has a significant issue, unfortunately. Our DatabaseModule class connects to a real PostgreSQL database. For unit tests to be independent and reliable, we should avoid that.

Removing the DatabaseModule from our imports causes an issue, though.

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

To solve this problem, we need to notice that the UsersService class uses the database under the hood. We can avoid that by providing a mocked version of the UsersService.

It might make sense to refrain from mocking entire modules when writing unit tests. By doing that we would avoid testing how modules and classes interact with each other and test the parts of our system in isolation.
authentication.service.test.ts
1import { AuthenticationService } from './authentication.service';
2import { JwtModule } from '@nestjs/jwt';
3import { ConfigModule } from '@nestjs/config';
4import { Test } from '@nestjs/testing';
5import { SignUpDto } from './dto/signUp.dto';
6import { UsersService } from '../users/users.service';
7 
8describe('The AuthenticationService', () => {
9  let signUpData: SignUpDto;
10  let authenticationService: AuthenticationService;
11  beforeEach(async () => {
12    signUpData = {
13      email: 'john@smith.com',
14      name: 'John',
15      password: 'strongPassword123',
16    };
17    const module = await Test.createTestingModule({
18      providers: [
19        AuthenticationService,
20        {
21          provide: UsersService,
22          useValue: {
23            create: jest.fn().mockReturnValue(signUpData),
24          },
25        },
26      ],
27      imports: [
28        ConfigModule.forRoot(),
29        JwtModule.register({
30          secretOrPrivateKey: 'Secret key',
31        }),
32      ],
33    }).compile();
34 
35    authenticationService = await module.get(AuthenticationService);
36  });
37  describe('when calling the getCookieForLogOut method', () => {
38    it('should return a correct string', () => {
39      const result = authenticationService.getCookieForLogOut();
40      expect(result).toBe('Authentication=; HttpOnly; Path=/; Max-Age=0');
41    });
42  });
43  describe('when registering a new user', () => {
44    describe('and when the usersService returns the new user', () => {
45      it('should return the new user', async () => {
46        const result = await authenticationService.signUp(signUpData);
47        expect(result).toBe(signUpData);
48      });
49    });
50  });
51});
PASS src/authentication/authentication.service.test.ts The AuthenticationService when calling the getCookieForLogOut method ✓ should return a correct string when registering a new user and when the usersService returns the new user ✓ should return the new user

Mocking the UsersService class gives us the confidence that our tests won’t use the actual database.

Changing the mock per test

In the test above, we mock the getByEmail method always to return a valid user. However, that’s not always true:

  • when we type the email of an existing user in our database, the method returns the user.
  • if the user with that specific email doesn’t exist, it throws the NotFoundException.

Let’s create a mock that covers both cases.

authentication.service.test.ts
1import { AuthenticationService } from './authentication.service';
2import { JwtModule } from '@nestjs/jwt';
3import { ConfigModule } from '@nestjs/config';
4import { Test } from '@nestjs/testing';
5import { SignUpDto } from './dto/signUp.dto';
6import { UsersService } from '../users/users.service';
7import { User } from '../users/user.model';
8import * as bcrypt from 'bcrypt';
9import { BadRequestException, NotFoundException } from '@nestjs/common';
10 
11describe('The AuthenticationService', () => {
12  let signUpData: SignUpDto;
13  let authenticationService: AuthenticationService;
14  let getByEmailMock: jest.Mock;
15  let password: string;
16  beforeEach(async () => {
17    getByEmailMock = jest.fn();
18    password = 'strongPassword123';
19    signUpData = {
20      password,
21      email: 'john@smith.com',
22      name: 'John',
23    };
24    const module = await Test.createTestingModule({
25      providers: [
26        AuthenticationService,
27        {
28          provide: UsersService,
29          useValue: {
30            create: jest.fn().mockReturnValue(signUpData),
31            getByEmail: getByEmailMock,
32          },
33        },
34      ],
35      imports: [
36        ConfigModule.forRoot(),
37        JwtModule.register({
38          secretOrPrivateKey: 'Secret key',
39        }),
40      ],
41    }).compile();
42 
43    authenticationService = await module.get(AuthenticationService);
44  });
45  describe('when calling the getCookieForLogOut method', () => {
46    // ...
47  });
48  describe('when registering a new user', () => {
49    // ...
50  });
51  describe('when the getAuthenticatedUser method is called', () => {
52    describe('and a valid email and password are provided', () => {
53      let userData: User;
54      beforeEach(async () => {
55        const hashedPassword = await bcrypt.hash(password, 10);
56        userData = {
57          id: 1,
58          email: 'john@smith.com',
59          name: 'John',
60          password: hashedPassword,
61        };
62        getByEmailMock.mockResolvedValue(userData);  // 👈
63      });
64      it('should return the new user', async () => {
65        const result = await authenticationService.getAuthenticatedUser(
66          userData.email,
67          password,
68        );
69        expect(result).toBe(userData);
70      });
71    });
72    describe('and an invalid email is provided', () => {
73      beforeEach(() => {
74        getByEmailMock.mockRejectedValue(new NotFoundException());  // 👈
75      });
76      it('should throw the BadRequestException', () => {
77        return expect(async () => {
78          await authenticationService.getAuthenticatedUser(
79            'john@smith.com',
80            password,
81          );
82        }).rejects.toThrow(BadRequestException);
83      });
84    });
85  });
86});
The AuthenticationService when calling the getCookieForLogOut method ✓ should return a correct string when registering a new user and when the usersService returns the new user ✓ should return the new user when the getAuthenticatedUser method is called and a valid email and password are provided ✓ should return the new user and an invalid email is provided ✓ should throw the BadRequestException

Above, we create the getByEmailMock variable and use it in the mocked UsersService. Then, we use the getByEmailMock.mockResolvedValue method to change the value returned by the getByEmail method.

An important thing to notice is that we are focusing on testing the logic contained in the methods of the AuthenticationService while making sure that the tests don’t rely on the code of the UsersService.

Mocking Kysely

So far, we haven’t tested a class that uses Kysely directly. Let’s take a look at the create method in the UsersRepository.

users.repository.ts
1import { BadRequestException, Injectable } from '@nestjs/common';
2import { User } from './user.model';
3import { CreateUserDto } from './dto/createUser.dto';
4import { Database } from '../database/database';
5import { isDatabaseError } from '../types/databaseError';
6import { PostgresErrorCode } from '../database/postgresErrorCode.enum';
7 
8@Injectable()
9export class UsersRepository {
10  constructor(private readonly database: Database) {}
11 
12  async create(userData: CreateUserDto) {
13    try {
14      const databaseResponse = await this.database
15        .insertInto('users')
16        .values({
17          password: userData.password,
18          email: userData.email,
19          name: userData.name,
20        })
21        .returningAll()
22        .executeTakeFirstOrThrow();
23 
24      return new User(databaseResponse);
25    } catch (error) {
26      if (
27        isDatabaseError(error) &&
28        error.code === PostgresErrorCode.UniqueViolation
29      ) {
30        throw new BadRequestException('User with this email already exists');
31      }
32      throw error;
33    }
34  }
35 
36  // ...
37}

Above, we can see two cases:

  • if the database manages to create a new row in the table, the create method returns an instance of the User class,
  • if Kysely throws an error because the user with a particular email already exists, the create method throws the BadRequestException.

To test both situations, we need to mock Kysely. A very important thing to notice is that we are chaining the insertInto, values, and returningAll methods. Because of that, they all should return an instance of Kysely. To achieve that, we can use jest.fn().mockReturnThis().

users.repository.test.ts
1import { CreateUserDto } from './dto/createUser.dto';
2import { Test } from '@nestjs/testing';
3import { UsersRepository } from './users.repository';
4import { Database } from '../database/database';
5 
6describe('The UsersRepository class', () => {
7  let executeTakeFirstOrThrowMock: jest.Mock;
8  let createUserData: CreateUserDto;
9  let usersRepository: UsersRepository;
10  beforeEach(async () => {
11    createUserData = {
12      name: 'John',
13      email: 'john@smith.com',
14      password: 'strongPassword123',
15    };
16    executeTakeFirstOrThrowMock = jest.fn();
17    const module = await Test.createTestingModule({
18      providers: [
19        UsersRepository,
20        {
21          provide: Database,
22          useValue: {
23            insertInto: jest.fn().mockReturnThis(),
24            values: jest.fn().mockReturnThis(),
25            returningAll: jest.fn().mockReturnThis(),
26            executeTakeFirstOrThrow: executeTakeFirstOrThrowMock,
27          },
28        },
29      ],
30    }).compile();
31 
32    usersRepository = await module.get(UsersRepository);
33  });
34 
35  // ...
36});

Please notice that we are not using jest.fn().mockReturnThis() for the executeTakeFirstOrThrow method. Instead, we will change this mock based on the test case.

users.repository.test.ts
1import { CreateUserDto } from './dto/createUser.dto';
2import { Test } from '@nestjs/testing';
3import { UsersRepository } from './users.repository';
4import { User, UserModelData } from './user.model';
5import { DatabaseError } from '../types/databaseError';
6import { PostgresErrorCode } from '../database/postgresErrorCode.enum';
7import { Database } from '../database/database';
8import { BadRequestException } from '@nestjs/common';
9 
10describe('The UsersRepository class', () => {
11  let executeTakeFirstOrThrowMock: jest.Mock;
12  let createUserData: CreateUserDto;
13  let usersRepository: UsersRepository;
14  beforeEach(async () => {
15    createUserData = {
16      name: 'John',
17      email: 'john@smith.com',
18      password: 'strongPassword123',
19    };
20    executeTakeFirstOrThrowMock = jest.fn();
21    const module = await Test.createTestingModule({
22      providers: [
23        UsersRepository,
24        {
25          provide: Database,
26          useValue: {
27            insertInto: jest.fn().mockReturnThis(),
28            values: jest.fn().mockReturnThis(),
29            returningAll: jest.fn().mockReturnThis(),
30            executeTakeFirstOrThrow: executeTakeFirstOrThrowMock,
31          },
32        },
33      ],
34    }).compile();
35 
36    usersRepository = await module.get(UsersRepository);
37  });
38  describe('when the create method is called', () => {
39    describe('and the database returns valid data', () => {
40      let userModelData: UserModelData;
41      beforeEach(() => {
42        userModelData = {
43          id: 1,
44          name: 'John',
45          email: 'john@smith.com',
46          password: 'strongPassword123',
47          address_id: null,
48          address_street: null,
49          address_city: null,
50          address_country: null,
51        };
52        executeTakeFirstOrThrowMock.mockResolvedValue(userModelData);
53      });
54      it('should return an instance of the UserModel', async () => {
55        const result = await usersRepository.create(createUserData);
56 
57        expect(result instanceof User).toBe(true);
58      });
59      it('should return the UserModel with correct properties', async () => {
60        const result = await usersRepository.create(createUserData);
61 
62        expect(result.id).toBe(userModelData.id);
63        expect(result.email).toBe(userModelData.email);
64        expect(result.name).toBe(userModelData.name);
65        expect(result.password).toBe(userModelData.password);
66        expect(result.address).not.toBeDefined();
67      });
68    });
69    describe('and the database throws the UniqueViolation', () => {
70      beforeEach(() => {
71        const databaseError: DatabaseError = {
72          code: PostgresErrorCode.UniqueViolation,
73          table: 'users',
74          detail: 'Key (email)=(john@smith.com) already exists.',
75        };
76        executeTakeFirstOrThrowMock.mockImplementation(() => {
77          throw databaseError;
78        });
79      });
80      it('should throw the BadRequestException exception', () => {
81        return expect(() =>
82          usersRepository.create(createUserData),
83        ).rejects.toThrow(BadRequestException);
84      });
85    });
86  });
87});
PASS src/users/users.repository.test.ts The UsersRepository class when the create method is called and the database returns valid data ✓ should return an instance of the UserModel ✓ should return the UserModel with correct properties and the database throws the UniqueViolation ✓ should throw the BadRequestException exception

Above, we test both cases by setting the mocked executeTakeFirstOrThrow method to either return the user data or throw an error.

Summary

In this article, we’ve explained the concept of unit tests and their implementation in the context of NestJS. Our primary focus has been on testing the components of our application that interact with the database. Since unit tests should avoid using a real database connection, we’ve explored the technique of mocking our services and repositories. We also learned how to mock the Kysely library. All of the above serves as a good starting point for testing a NestJS project that uses SQL and Kysely.