How to Use Test Module in NestJS for Unit Testing
In NestJS, use the
Test module from @nestjs/testing to create a testing module that mimics your app module. This allows you to instantiate providers and controllers in isolation for unit testing with Test.createTestingModule() and compile().Syntax
The Test module provides a method createTestingModule() which accepts a module metadata object similar to a regular NestJS module. After defining providers, controllers, and imports, call compile() to build the testing module. Then use get() to retrieve instances for testing.
- createTestingModule({}): Defines the test module with
providers,controllers, andimports. - compile(): Compiles the module and returns a
TestingModuleinstance. - get(token): Retrieves an instance of a provider or controller from the compiled module.
typescript
const moduleRef = await Test.createTestingModule({ providers: [MyService], controllers: [MyController], imports: [OtherModule], }).compile(); const service = moduleRef.get<MyService>(MyService);
Example
This example shows how to test a simple service using the Test module. It creates a testing module with the service provider, compiles it, and then tests a method.
typescript
import { Test, TestingModule } from '@nestjs/testing'; import { MyService } from './my.service'; describe('MyService', () => { let service: MyService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [MyService], }).compile(); service = module.get<MyService>(MyService); }); it('should return expected value', () => { expect(service.getHello()).toBe('Hello World!'); }); }); // my.service.ts export class MyService { getHello(): string { return 'Hello World!'; } }
Output
PASS MyService
โ should return expected value (5 ms)
Common Pitfalls
Common mistakes when using the Test module include:
- Not calling
compile()before accessing providers, which causes errors. - Forgetting to include all required providers or imports, leading to undefined dependencies.
- Trying to test asynchronous providers without using
async/awaitproperly.
Always ensure your test module mimics the real module dependencies needed for the test.
typescript
/* Wrong: Missing compile() call */ const moduleRef = Test.createTestingModule({ providers: [MyService], }); const service = moduleRef.get<MyService>(MyService); // Error: moduleRef is a Promise /* Right: Use await and compile() */ const moduleRef = await Test.createTestingModule({ providers: [MyService], }).compile(); const service = moduleRef.get<MyService>(MyService);
Quick Reference
Summary tips for using the NestJS Test module:
- Always use
await Test.createTestingModule(...).compile()to build the test module. - Include all necessary
providers,controllers, andimportsto avoid missing dependencies. - Use
moduleRef.get()to retrieve instances for testing. - Use
beforeEachto set up fresh module instances for isolated tests.
Key Takeaways
Use Test.createTestingModule() with compile() to create isolated test modules.
Include all required providers and imports to avoid dependency errors.
Retrieve service or controller instances with moduleRef.get() for testing.
Always await compile() to ensure the module is ready before tests run.
Use beforeEach to reset the test environment for each test case.