Unit tests with PostgreSQL and Kysely
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…
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 { // ... "jest": { "testRegex": ".*\\.(spec|test)\\.ts$", // ... } }Let’s start by creating a simple test for our AuthenticationService class. authentication.service.test.ts import { AuthenticationService } from './authentication.service'; import { JwtService } from '@nestjs/jwt'; import { ConfigService } from '@nestjs/config'; import { Pool } from 'pg'; import { UsersService } from '../users/users.service'; import { UsersRepository } from '../users/users.repository'; import { Database } from '../database/database'; import { PostgresDialect } from 'kysely'; describe('The AuthenticationService', () => { let authenticationService: AuthenticationService; beforeEach(() => { const configService = new ConfigService(); authenticationService = new AuthenticationService( new UsersService( new UsersRepository( new Database({ dialect: new PostgresDialect({ pool: new Pool({ host: configService.get('POSTGRES_HOST'), port: configService.get('POSTGRES_PORT'), user: configService.get('POSTGRES_USER'), password: configService.get('POSTGRES_PASSWORD'), database: configService.get('POSTGRES_DB'), }), }), }), ), ), new JwtService({ secretOrPrivateKey: 'Secret key', }), new ConfigService(), ); }); describe('when calling the getCookieForLogOut method', () => { it('should return a correct string', () => { const result = authenticationService.getCookieForLogOut(); expect(result).toBe('Authentication=; HttpOnly; Path=/; Max-Age=0'); }); }); }); 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 import { AuthenticationService } from './authentication.service'; import { JwtModule } from '@nestjs/jwt'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { DatabaseModule } from '../database/database.module'; import { UsersModule } from '../users/users.module'; import { Test } from '@nestjs/testing'; import { EnvironmentVariables } from '../types/environmentVariables'; describe('The AuthenticationService', () => { let authenticationService: AuthenticationService; beforeEach(async () => { const module = await Test.createTestingModule({ providers: [AuthenticationService], imports: [ UsersModule, ConfigModule.forRoot(), JwtModule.register({ secretOrPrivateKey: 'Secret key', }), DatabaseModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: ( configService: ConfigService<EnvironmentVariables, true>, ) => ({ host: configService.get('POSTGRES_HOST'), port: configService.get('POSTGRES_PORT'), user: configService.get('POSTGRES_USER'), password: configService.get('POSTGRES_PASSWORD'), database: configService.get('POSTGRES_DB'), }), }), ], }).compile(); authenticationService = await module.get(AuthenticationService); }); describe('when calling the getCookieForLogOut method', () => { it('should return a correct string', () => { const result = authenticationService.getCookieForLogOut(); expect(result).toBe('Authentication=; HttpOnly; Path=/; Max-Age=0'); }); }); });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 import { AuthenticationService } from './authentication.service'; import { JwtModule } from '@nestjs/jwt'; import { ConfigModule } from '@nestjs/config'; import { Test } from '@nestjs/testing'; import { SignUpDto } from './dto/signUp.dto'; import { UsersService } from '../users/users.service'; describe('The AuthenticationService', () => { let signUpData: SignUpDto; let authenticationService: AuthenticationService; beforeEach(async () => { signUpData = { email: 'john@smith.com', name: 'John', password: 'strongPassword123', }; const module = await Test.createTestingModule({ providers: [ AuthenticationService, { provide: UsersService, useValue: { create: jest.fn().mockReturnValue(signUpData), }, }, ], imports: [ ConfigModule.forRoot(), JwtModule.register({ secretOrPrivateKey: 'Secret key', }), ], }).compile(); authenticationService = await module.get(AuthenticationService); }); describe('when calling the getCookieForLogOut method', () => { it('should return a correct string', () => { const result = authenticationService.getCookieForLogOut(); expect(result).toBe('Authentication=; HttpOnly; Path=/; Max-Age=0'); }); }); describe('when registering a new user', () => { describe('and when the usersService returns the new user', () => { it('should return the new user', async () => { const result = await authenticationService.signUp(signUpData); expect(result).toBe(signUpData); }); }); }); }); 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 import { AuthenticationService } from './authentication.service'; import { JwtModule } from '@nestjs/jwt'; import { ConfigModule } from '@nestjs/config'; import { Test } from '@nestjs/testing'; import { SignUpDto } from './dto/signUp.dto'; import { UsersService } from '../users/users.service'; import { User } from '../users/user.model'; import * as bcrypt from 'bcrypt'; import { BadRequestException, NotFoundException } from '@nestjs/common'; describe('The AuthenticationService', () => { let signUpData: SignUpDto; let authenticationService: AuthenticationService; let getByEmailMock: jest.Mock; let password: string; beforeEach(async () => { getByEmailMock = jest.fn(); password = 'strongPassword123'; signUpData = { password, email: 'john@smith.com', name: 'John', }; const module = await Test.createTestingModule({ providers: [ AuthenticationService, { provide: UsersService, useValue: { create: jest.fn().mockReturnValue(signUpData), getByEmail: getByEmailMock, }, }, ], imports: [ ConfigModule.forRoot(), JwtModule.register({ secretOrPrivateKey: 'Secret key', }), ], }).compile(); authenticationService = await module.get(AuthenticationService); }); describe('when calling the getCookieForLogOut method', () => { // ... }); describe('when registering a new user', () => { // ... }); describe('when the getAuthenticatedUser method is called', () => { describe('and a valid email and password are provided', () => {