DEV Community

mark vachi
mark vachi

Posted on • Updated on


How to Create a Unit Test for a NestJS Service with a TypeORM Repository (MySQL)

NestJS is a great framework for building scalable and modular server-side applications. One of its key features is the ability to easily inject dependencies, including TypeORM repositories, into your service classes. In this tutorial, we'll show you how to create a unit test for a service that uses a TypeORM repository in a MySQL database.

First, let's take a look at how to inject the task repository into our service class:

// task.servic.ts

export class TaskService {
    private readonly taskRepository: Repository<Task>,
  ) {}
Enter fullscreen mode Exit fullscreen mode

We can then use the TypeOrmModule to configure the database connection in our AppModule. However, for testing purposes, it's a good idea to separate this configuration into a separate file that can be imported into our testing module. This keeps our code clean and makes it easier to reuse for testing other parts of our application.

Here's an example of how to create a database configuration file for testing:

// src/test-utils/TypeORMMySqlTestingModule.ts

import { TypeOrmModule } from '@nestjs/typeorm';

export const TypeORMMySqlTestingModule = (entities: any[]) =>
    type: 'mysql',
    host: process.env.MYSQL_HOST || 'localhost',
    port: 3306,
    username: process.env.MYSQL_USERNAME || 'nest',
    password: process.env.MYSQL_PASSWORD || 'nest',
    database: process.env.MYSQL_DATABASE || 'test',
    entities: [...entities],
    synchronize: true,
Enter fullscreen mode Exit fullscreen mode

Then, in our testing module, we can import this configuration file and use it to set up our database connection:

// task.service.spac.ts
beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
      providers: [TaskService],

    service = module.get<TaskService>(TaskService);
Enter fullscreen mode Exit fullscreen mode

Finally, we can run our tests by using the following command:

$ yarn test src/task/task.service.spec.ts
Enter fullscreen mode Exit fullscreen mode

And that's it! You now have a fully functional unit test for a NestJS service with a TypeORM repository in a MySQL database.

For more information, check out the following resources:

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.