11 min read

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…

October 30, 2023

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 { ConfigService } from "@nestjs/config"
import { JwtService } from "@nestjs/jwt"
import { PostgresDialect } from "kysely"
import { Pool } from "pg"
 
import { Database } from "../database/database"
import { UsersRepository } from "../users/users.repository"
import { UsersService } from "../users/users.service"
import { AuthenticationService } from "./authentication.service"
 
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 { ConfigModule, ConfigService } from "@nestjs/config"
import { JwtModule } from "@nestjs/jwt"
import { Test } from "@nestjs/testing"
 
import { DatabaseModule } from "../database/database.module"
import { EnvironmentVariables } from "../types/environmentVariables"
import { UsersModule } from "../users/users.module"
import { AuthenticationService } from "./authentication.service"
 
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 { ConfigModule } from "@nestjs/config"
import { JwtModule } from "@nestjs/jwt"
import { Test } from "@nestjs/testing"
 
import { UsersService } from "../users/users.service"
import { AuthenticationService } from "./authentication.service"
import { SignUpDto } from "./dto/signUp.dto"
 
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 { BadRequestException, NotFoundException } from "@nestjs/common"
import { ConfigModule } from "@nestjs/config"
import { JwtModule } from "@nestjs/jwt"
import { Test } from "@nestjs/testing"
import * as bcrypt from "bcrypt"
 
import { User } from "../users/user.model"
import { UsersService } from "../users/users.service"
import { AuthenticationService } from "./authentication.service"
import { SignUpDto } from "./dto/signUp.dto"
 
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", () => {
      let userData: User
      beforeEach(async () => {
        const hashedPassword = await bcrypt.hash(password, 10)
        userData = {
          id: 1,
          email: "john@smith.com",
          name: "John",
          password: hashedPassword,
        }
        getByEmailMock.mockResolvedValue(userData) // 👈
      })
      it("should return the new user", async () => {
        const result = await authenticationService.getAuthenticatedUser(userData.email, password)
        expect(result).toBe(userData)
      })
    })
    describe("and an invalid email is provided", () => {
      beforeEach(() => {
        getByEmailMock.mockRejectedValue(new NotFoundException()) // 👈
      })
      it("should throw the BadRequestException", () => {
        return expect(async () => {
          await authenticationService.getAuthenticatedUser("john@smith.com", password)
        }).rejects.toThrow(BadRequestException)
      })
    })
  })
})

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#
import { BadRequestException, Injectable } from "@nestjs/common"
import { User } from "./user.model"
import { CreateUserDto } from "./dto/createUser.dto"
import { Database } from "../database/database"
import { isDatabaseError } from "../types/databaseError"
import { PostgresErrorCode } from "../database/postgresErrorCode.enum"
@Injectable()
export class UsersRepository {
  constructor(private readonly database: Database) {}
  async create(userData: CreateUserDto) {
    try {
      const databaseResponse = await this.database
        .insertInto("users")
        .values({
          password: userData.password,
          email: userData.email,
          name: userData.name,
        })
        .returningAll()
        .executeTakeFirstOrThrow()
      return new User(databaseResponse)
    } catch (error) {
      if (isDatabaseError(error) && error.code === PostgresErrorCode.UniqueViolation) {
        throw new BadRequestException("User with this email already exists")
      }
      throw error
    }
  } // ...
}

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#
import { Test } from "@nestjs/testing"
 
import { Database } from "../database/database"
import { CreateUserDto } from "./dto/createUser.dto"
import { UsersRepository } from "./users.repository"
 
describe("The UsersRepository class", () => {
  let executeTakeFirstOrThrowMock: jest.Mock
  let createUserData: CreateUserDto
  let usersRepository: UsersRepository
  beforeEach(async () => {
    createUserData = {
      name: "John",
      email: "john@smith.com",
      password: "strongPassword123",
    }
    executeTakeFirstOrThrowMock = jest.fn()
    const module = await Test.createTestingModule({
      providers: [
        UsersRepository,
        {
          provide: Database,
          useValue: {
            insertInto: jest.fn().mockReturnThis(),
            values: jest.fn().mockReturnThis(),
            returningAll: jest.fn().mockReturnThis(),
            executeTakeFirstOrThrow: executeTakeFirstOrThrowMock,
          },
        },
      ],
    }).compile()
    usersRepository = await module.get(UsersRepository)
  }) // ...
})

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#
import { BadRequestException } from "@nestjs/common"
import { Test } from "@nestjs/testing"
 
import { Database } from "../database/database"
import { PostgresErrorCode } from "../database/postgresErrorCode.enum"
import { DatabaseError } from "../types/databaseError"
import { CreateUserDto } from "./dto/createUser.dto"
import { User, UserModelData } from "./user.model"
import { UsersRepository } from "./users.repository"
 
describe("The UsersRepository class", () => {
  let executeTakeFirstOrThrowMock: jest.Mock
  let createUserData: CreateUserDto
  let usersRepository: UsersRepository
  beforeEach(async () => {
    createUserData = {
      name: "John",
      email: "john@smith.com",
      password: "strongPassword123",
    }
    executeTakeFirstOrThrowMock = jest.fn()
    const module = await Test.createTestingModule({
      providers: [
        UsersRepository,
        {
          provide: Database,
          useValue: {
            insertInto: jest.fn().mockReturnThis(),
            values: jest.fn().mockReturnThis(),
            returningAll: jest.fn().mockReturnThis(),
            executeTakeFirstOrThrow: executeTakeFirstOrThrowMock,
          },
        },
      ],
    }).compile()
    usersRepository = await module.get(UsersRepository)
  })
  describe("when the create method is called", () => {
    describe("and the database returns valid data", () => {
      let userModelData: UserModelData
      beforeEach(() => {
        userModelData = {
          id: 1,
          name: "John",
          email: "john@smith.com",
          password: "strongPassword123",
          address_id: null,
          address_street: null,
          address_city: null,
          address_country: null,
        }
        executeTakeFirstOrThrowMock.mockResolvedValue(userModelData)
      })
      it("should return an instance of the UserModel", async () => {
        const result = await usersRepository.create(createUserData)
        expect(result instanceof User).toBe(true)
      })
      it("should return the UserModel with correct properties", async () => {
        const result = await usersRepository.create(createUserData)
        expect(result.id).toBe(userModelData.id)
        expect(result.email).toBe(userModelData.email)
        expect(result.name).toBe(userModelData.name)
        expect(result.password).toBe(userModelData.password)
        expect(result.address).not.toBeDefined()
      })
    })
    describe("and the database throws the UniqueViolation", () => {
      beforeEach(() => {
        const databaseError: DatabaseError = {
          code: PostgresErrorCode.UniqueViolation,
          table: "users",
          detail: "Key (email)=(john@smith.com) already exists.",
        }
        executeTakeFirstOrThrowMock.mockImplementation(() => {
          throw databaseError
        })
      })
      it("should throw the BadRequestException exception", () => {
        return expect(() => usersRepository.create(createUserData)).rejects.toThrow(
          BadRequestException,
        )
      })
    })
  })
})

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.

Unit tests with PostgreSQL and Kysely | NestJS.io