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.
Previous
What is the NestJS Queue module?
Next
What is the NestJS interceptor for response transformation?
More NestJS Questions
View all →- Intermediate How does NestJS dependency injection scoping work?
- Intermediate What are NestJS microservices and what transports are supported?
- Intermediate What is the ExecutionContext in NestJS?
- Intermediate How do you implement role-based access control (RBAC) in NestJS?
- Intermediate What is the Reflector in NestJS and how is it used?