0
# Module Building
1
2
Core functionality for creating isolated test modules with dependency injection. This is the foundation of NestJS testing, allowing developers to create minimal test environments that mirror production module structures.
3
4
## Capabilities
5
6
### Test Class
7
8
The main entry point for creating testing modules. Provides a static method to initialize the test module building process.
9
10
```typescript { .api }
11
/**
12
* Main entry point for creating testing modules
13
*/
14
class Test {
15
/**
16
* Creates a TestingModuleBuilder for configuring a test module
17
* @param metadata - Module metadata defining providers, controllers, imports, etc.
18
* @param options - Optional configuration for the testing module
19
* @returns TestingModuleBuilder instance for chaining configuration methods
20
*/
21
static createTestingModule(
22
metadata: ModuleMetadata,
23
options?: TestingModuleOptions
24
): TestingModuleBuilder;
25
}
26
```
27
28
**Usage Examples:**
29
30
```typescript
31
import { Test } from "@nestjs/testing";
32
import { UsersModule } from "./users.module";
33
import { UsersService } from "./users.service";
34
35
// Basic module creation
36
const moduleBuilder = Test.createTestingModule({
37
providers: [UsersService],
38
});
39
40
// Module with imports
41
const moduleWithImports = Test.createTestingModule({
42
imports: [UsersModule],
43
providers: [UsersService],
44
});
45
46
// With custom options
47
const moduleWithOptions = Test.createTestingModule(
48
{
49
providers: [UsersService],
50
},
51
{
52
moduleIdGeneratorAlgorithm: "uuid",
53
}
54
);
55
```
56
57
### TestingModuleBuilder
58
59
Builder pattern class for configuring testing modules. Provides methods for setting up overrides and compiling the final test module.
60
61
```typescript { .api }
62
/**
63
* Builder for configuring and compiling testing modules
64
*/
65
class TestingModuleBuilder {
66
/**
67
* Sets a custom logger for the testing module
68
* @param testingLogger - Logger service implementation
69
* @returns TestingModuleBuilder for method chaining
70
*/
71
setLogger(testingLogger: LoggerService): TestingModuleBuilder;
72
73
/**
74
* Compiles the testing module with all configured overrides
75
* @param options - Optional compilation options for snapshots and previews
76
* @returns Promise resolving to a compiled TestingModule
77
*/
78
compile(
79
options?: Pick<NestApplicationContextOptions, "snapshot" | "preview">
80
): Promise<TestingModule>;
81
}
82
```
83
84
**Usage Examples:**
85
86
```typescript
87
import { Test, TestingModule } from "@nestjs/testing";
88
import { Logger } from "@nestjs/common";
89
90
// Basic compilation
91
const module: TestingModule = await Test.createTestingModule({
92
providers: [UsersService],
93
}).compile();
94
95
// With custom logger
96
const moduleWithLogger = await Test.createTestingModule({
97
providers: [UsersService],
98
})
99
.setLogger(new Logger())
100
.compile();
101
102
// With snapshot for deterministic testing
103
const moduleWithSnapshot = await Test.createTestingModule({
104
providers: [UsersService],
105
}).compile({ snapshot: true });
106
```
107
108
### TestingModule
109
110
The compiled testing module that provides dependency injection and can create full NestJS applications.
111
112
```typescript { .api }
113
/**
114
* Compiled testing module extending NestJS application context
115
*/
116
class TestingModule extends NestApplicationContext {
117
/**
118
* Gets an instance of a provider, controller, or injectable from the module
119
* @param typeOrToken - Class constructor or injection token
120
* @param options - Optional resolution options
121
* @returns Instance of the requested provider
122
*/
123
get<TInput = any, TResult = TInput>(
124
typeOrToken: Type<TInput> | Function | string | symbol,
125
options?: GetOrResolveOptions
126
): TResult;
127
128
/**
129
* Resolves an instance asynchronously
130
* @param typeOrToken - Class constructor or injection token
131
* @param contextId - Optional context identifier for scoped providers
132
* @param options - Optional resolution options
133
* @returns Promise resolving to the requested instance
134
*/
135
resolve<TInput = any, TResult = TInput>(
136
typeOrToken: Type<TInput> | Function | string | symbol,
137
contextId?: ContextId,
138
options?: ResolveOptions
139
): Promise<TResult>;
140
141
/**
142
* Closes the testing module and cleans up resources
143
* @returns Promise that resolves when cleanup is complete
144
*/
145
close(): Promise<void>;
146
}
147
```
148
149
**Usage Examples:**
150
151
```typescript
152
import { Test, TestingModule } from "@nestjs/testing";
153
import { UsersService } from "./users.service";
154
import { DatabaseService } from "./database.service";
155
156
describe("UsersService", () => {
157
let module: TestingModule;
158
let usersService: UsersService;
159
let databaseService: DatabaseService;
160
161
beforeEach(async () => {
162
module = await Test.createTestingModule({
163
providers: [UsersService, DatabaseService],
164
}).compile();
165
166
// Get service instances
167
usersService = module.get<UsersService>(UsersService);
168
databaseService = module.get<DatabaseService>(DatabaseService);
169
});
170
171
afterEach(async () => {
172
// Clean up resources
173
await module.close();
174
});
175
176
it("should retrieve users from database", async () => {
177
// Test implementation
178
});
179
});
180
181
// Using resolve for async initialization
182
const asyncService = await module.resolve<AsyncService>(AsyncService);
183
```
184
185
## Types
186
187
```typescript { .api }
188
import { ModuleMetadata } from "@nestjs/common/interfaces/modules/module-metadata.interface";
189
import { NestApplicationContextOptions } from "@nestjs/common/interfaces/nest-application-context-options.interface";
190
import { LoggerService, Type } from "@nestjs/common";
191
import { ContextId } from "@nestjs/core";
192
193
interface TestingModuleOptions {
194
moduleIdGeneratorAlgorithm?: "uuid" | "timestamp";
195
}
196
197
interface GetOrResolveOptions {
198
strict?: boolean;
199
each?: boolean;
200
}
201
202
interface ResolveOptions {
203
strict?: boolean;
204
}
205
```