乐闻世界logo
搜索文章和话题

How to unit test a custom repository of TypeORM in NestJS?

1个答案

1

When using TypeORM in NestJS, unit testing requires ensuring code testability and proper dependency management. Below, I will provide a detailed explanation of how to unit test a custom TypeORM repository.

Step 1: Setting Up the Test Environment

First, ensure that your test environment is configured. This typically means you have already installed Jest and the @nestjs/testing module in your project.

Step 2: Creating the Repository Mock

To perform unit testing, we need to mock the TypeORM repository. Here, you can use jest.mock() or NestJS's @InjectRepository() decorator to inject a mock repository. For example, suppose you have a custom repository named UsersRepository:

typescript
import { EntityRepository, Repository } from 'typeorm'; import { User } from './entities/user.entity'; @EntityRepository(User) export class UsersRepository extends Repository<User> { findByName(name: string): Promise<User | undefined> { return this.findOne({ name }); } }

You can create a mock version of this repository:

typescript
const mockUsersRepository = () => ({ findByName: jest.fn().mockResolvedValue(mockUser), });

Step 3: Configuring the TestingModule

Next, in your test file, use NestJS's Test module to configure your test environment. Ensure that the real repository instance is replaced with a mock instance:

typescript
import { Test, TestingModule } from '@nestjs/testing'; import { UsersService } from './users.service'; import { UsersRepository } from './users.repository'; describe('UsersService', () => { let service: UsersService; let repository: ReturnType<typeof mockUsersRepository>; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [ UsersService, { provide: UsersRepository, useFactory: mockUsersRepository, }, ], }).compile(); service = module.get<UsersService>(UsersService); repository = module.get<UsersRepository>(UsersRepository); }); it('should be defined', () => { expect(service).toBeDefined(); expect(repository).toBeDefined(); }); // Additional tests... });

Step 4: Writing Unit Tests

Now, you can write unit tests for your UsersService or directly for methods in UsersRepository. For example, testing the findByName method:

typescript
describe('findByName', () => { it('should return a user by name', async () => { const user = await service.findByName('Alice'); expect(user).toEqual(mockUser); expect(repository.findByName).toHaveBeenCalledWith('Alice'); }); });

In this test, we verify that when findByName is called, it returns the expected user object and that the method is correctly invoked.

Summary By following these steps, you can effectively unit test a custom TypeORM repository used in NestJS. The key is to use mocks to isolate tests, ensuring no dependency on external databases or other services while maintaining test independence and repeatability.

2024年8月3日 17:00 回复

你的答案