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.
0
0
Testing module setup in NestJS
Introduction
When you want to test a service or controller in isolation.
When you need to mock dependencies to avoid real database or API calls.
When you want to check if your module's providers are correctly wired.
When you want to run automated tests during development.
When you want to ensure your code changes don't break existing features.
Syntax
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.
Examples
This sets up a test module with only one service provider.
NestJS
const module = await Test.createTestingModule({
providers: [MyService],
}).compile();This sets up a test module with a controller and its service.
NestJS
const module = await Test.createTestingModule({
controllers: [MyController],
providers: [MyService],
}).compile();This includes another module to provide dependencies like database connections.
NestJS
const module = await Test.createTestingModule({
imports: [DatabaseModule],
providers: [MyService],
}).compile();Sample Program
This test sets up a module with HelloService. It checks if the getHello method returns the expected greeting.
NestJS
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!'); }); });
OutputSuccess
Important Notes
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.
Summary
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.