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

@Injectable()
export class TaskService {
  constructor(
    @InjectRepository(Task)
    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[]) =>
  TypeOrmModule.forRoot({
    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: [
        TypeORMMySqlTestingModule([Task]),
        TypeOrmModule.forFeature([Task]),
      ],
      providers: [TaskService],
    }).compile();

    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 (2)

Collapse
 
juandardilag profile image
JuanDArdilaG

That doesn't seem like a unit test since you use an actual mysql connection.

Collapse
 
m4r14 profile image
mark vachi

Yes, Unit test shouldn't connect with Database. I wrote this article before I understood this.