Trung BìnhNestJS iconNestJS

Cách viết unit tests và integration tests trong NestJS?

NestJS dùng Jest và cung cấp Test.createTestingModule() để tạo test environment với DI container đầy đủ.

Unit test service: tạo mock repository với jest.fn() cho mỗi method, đăng ký trong module với { provide: getRepositoryToken(Entity), useValue: mockRepo }. Test từng method riêng lẻ, verify calls với expect(mock).toHaveBeenCalledWith(), reset mocks với jest.clearAllMocks() sau mỗi test.

E2E/Integration test: dùng Test.createTestingModule({ imports: [AppModule] }), override providers với .overrideProvider(Service).useValue(mockService), tạo app với moduleFixture.createNestApplication(), init global pipes/guards, dùng supertest để call real HTTP endpoints. Ưu tiên override service thay vì repository cho integration tests để test controller + service logic mà không cần DB thật.

Xem toàn bộ NestJS cùng filter theo level & chủ đề con.

Mở danh sách NestJS