Testing module setup helps you create a small, safe space to check if parts of your NestJS app work correctly. It keeps tests organized and easy to run.
Testing module setup in NestJS
import { Test, TestingModule } from '@nestjs/testing'; let module: TestingModule; beforeEach(async () => { module = await Test.createTestingModule({ imports: [], controllers: [], providers: [], }).compile(); });
The Test.createTestingModule method creates a test module similar to your app module.
You can add imports, controllers, and providers to mimic your real module.
const module = await Test.createTestingModule({
providers: [MyService],
}).compile();const module = await Test.createTestingModule({
controllers: [MyController],
providers: [MyService],
}).compile();const module = await Test.createTestingModule({
imports: [DatabaseModule],
providers: [MyService],
}).compile();This test sets up a module with HelloService. It checks if the getHello method returns the expected greeting.
import { Test, TestingModule } from '@nestjs/testing'; import { Injectable } from '@nestjs/common'; @Injectable() class HelloService { getHello(): string { return 'Hello, NestJS!'; } } describe('HelloService', () => { let service: HelloService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [HelloService], }).compile(); service = module.get<HelloService>(HelloService); }); it('should return greeting message', () => { expect(service.getHello()).toBe('Hello, NestJS!'); }); });
Always call compile() to finalize the test module before using it.
Use module.get() to retrieve instances of your providers for testing.
You can mock providers by replacing them in the providers array with custom objects.
Testing module setup creates a mini version of your app module for safe testing.
You add controllers, providers, and imports to match what you want to test.
Compile the module and get instances to run your tests easily.
Practice
Test.createTestingModule() in NestJS testing?Solution
Step 1: Understand the role of
This method creates a lightweight module for testing, including only what you add (controllers, providers, imports).Test.createTestingModule()Step 2: Compare with other options
Starting the full app server or deploying is not the purpose of this method. It is only for isolated testing setup.Final Answer:
To create a small test version of your app module with needed parts -> Option AQuick Check:
Testing module setup = small test module [OK]
- Thinking it starts the full app server
- Confusing with deployment or seeding
- Assuming it runs tests automatically
Solution
Step 1: Recall the async nature of
Thecompile()compile()method returns a Promise, so it must be awaited.Step 2: Check syntax correctness
Only await Test.createTestingModule({}).compile(); correctly usesawaitwithTest.createTestingModule({}).compile(). Others are either missing await or use invalid methods.Final Answer:
await Test.createTestingModule({}).compile(); -> Option DQuick Check:
Compile returns Promise, so use await [OK]
- Forgetting to await compile()
- Using non-existent compileTestingModule method
- Calling compile without parentheses
service.getData() return?
const moduleRef = await Test.createTestingModule({
providers: [{
provide: 'DataService',
useValue: { getData: () => 'mocked data' },
}],
}).compile();
const service = moduleRef.get('DataService');
return service.getData();Solution
Step 1: Identify the provider mock
The provider 'DataService' is mocked with an object whosegetDatamethod returns 'mocked data'.Step 2: Understand the get call
CallingmoduleRef.get('DataService')returns the mocked object, soservice.getData()returns 'mocked data'.Final Answer:
'mocked data' -> Option CQuick Check:
Mock provider method returns 'mocked data' [OK]
- Expecting real data instead of mock
- Assuming get returns undefined without provider
- Confusing provider token with class
const moduleRef = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
});
const controller = moduleRef.get(AppController);
Solution
Step 1: Check testing module lifecycle
After creating the testing module, you must callcompile()to finalize it before retrieving instances.Step 2: Identify missing compile call
The code does not callawait moduleRef.compile(), somoduleRef.get()will fail or behave unexpectedly.Final Answer:
Missing call to compile() before getting controller -> Option BQuick Check:
Always compile testing module before get() [OK]
- Forgetting to compile testing module
- Thinking controllers can't be added
- Trying to get by string token instead of class
Solution
Step 1: Understand dependency injection in testing
To replace a dependency, you provide a mock object usinguseValuein the providers array.Step 2: Setup providers correctly
Add the main service normally and add the dependency withprovideanduseValueto inject the mock.Final Answer:
Add the service and provide a mock usinguseValuefor the dependency in providers array -> Option AQuick Check:
Mock dependencies with useValue in providers [OK]
- Assuming NestJS auto-mocks dependencies
- Not providing mock for dependency
- Using imports instead of mocking for isolated tests
Ready to prove it?
Pass the test and this pattern moves unknown
