Does NestJS Work With Jest?
NestJS and Jest work together seamlessly with official integration and excellent tooling support.
Quick Facts
How NestJS Works With Jest
NestJS has built-in Jest support through the `@nestjs/testing` module, which provides utilities like `Test.createTestingModule()` for constructing isolated test environments. The framework's dependency injection system integrates perfectly with Jest's module mocking capabilities, allowing you to mock services, repositories, and external dependencies with minimal boilerplate. When you scaffold a NestJS project with the CLI, Jest is pre-configured with appropriate TypeScript support, module aliases, and coverage settings. The testing experience is streamlined: you create a testing module that mirrors your application's module structure, override providers with test doubles, and then test your controllers, services, and resolvers in complete isolation. This makes unit testing NestJS applications significantly cleaner than working with other Node frameworks.
Best Use Cases
Quick Setup
npm install --save-dev @nestjs/testing jest @types/jest ts-jestimport { Test, TestingModule } from '@nestjs/testing';
import { CatsService } from './cats.service';
import { CatsController } from './cats.controller';
describe('CatsController', () => {
let controller: CatsController;
let service: CatsService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [CatsController],
providers: [
{
provide: CatsService,
useValue: {
findAll: jest.fn().mockResolvedValue([{ id: 1, name: 'Fluffy' }]),
},
},
],
}).compile();
controller = module.get<CatsController>(CatsController);
service = module.get<CatsService>(CatsService);
});
it('should return an array of cats', async () => {
expect(await controller.findAll()).toEqual([{ id: 1, name: 'Fluffy' }]);
expect(service.findAll).toHaveBeenCalled();
});
});Known Issues & Gotchas
TypeScript path aliases not resolving in tests without proper jest.config.js configuration
Fix: Ensure moduleNameMapper is configured in jest.config.js to match tsconfig.json paths, or use the @nestjs/cli which handles this automatically
Async module initialization and lifecycle hooks not executing in tests
Fix: Call await app.init() after createTestingModule to ensure all async initializers and onModuleInit hooks run
Database connections persisting between test suites, causing test pollution
Fix: Use beforeAll/afterAll hooks to connect/disconnect, or better, use a test database that's wiped between test files
Alternatives
- •Vitest with NestJS - faster alternative with native ESM support and similar API
- •Mocha + Chai with NestJS - more traditional Node.js testing, requires manual setup
- •TypeORM with Sinon mocking - database-focused testing without Jest's module system
Resources
Related Compatibility Guides
Explore more compatibility guides