🦅 NestJS Intermediate

How do you write unit tests in NestJS?

Answer

NestJS uses Jest for testing and provides @nestjs/testing for creating test modules. For unit tests, create a lightweight test module: const module = await Test.createTestingModule({ providers: [UsersService, { provide: getRepositoryToken(User), useValue: mockRepo }] }).compile();. This creates an isolated DI container for the service being tested. Mock dependencies with jest.fn() or factory functions. Test the service: service = module.get<UsersService>(UsersService); expect(await service.findOne(1)).toEqual(mockUser);. For end-to-end tests, use the full module stack with NestFactory and Supertest. The test module pattern means you test the service in isolation with controlled, predictable dependencies.