0
# NestJS Testing
1
2
NestJS Testing provides comprehensive testing utilities for NestJS applications, enabling developers to create isolated testing environments with sophisticated dependency injection testing capabilities. The package offers tools for building test modules, overriding providers, and creating mock dependencies without bootstrapping the entire application.
3
4
## Package Information
5
6
- **Package Name**: @nestjs/testing
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @nestjs/testing`
10
11
## Core Imports
12
13
```typescript
14
import { Test, TestingModule } from "@nestjs/testing";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { Test, TestingModule } = require("@nestjs/testing");
21
```
22
23
Additional imports for advanced use cases:
24
25
```typescript
26
import {
27
OverrideBy,
28
OverrideByFactoryOptions,
29
MockFactory,
30
TestingModuleBuilder,
31
TestingModuleOptions,
32
} from "@nestjs/testing";
33
```
34
35
## Basic Usage
36
37
```typescript
38
import { Test, TestingModule } from "@nestjs/testing";
39
import { UsersService } from "./users.service";
40
import { UsersController } from "./users.controller";
41
42
describe("UsersController", () => {
43
let controller: UsersController;
44
let service: UsersService;
45
46
beforeEach(async () => {
47
const module: TestingModule = await Test.createTestingModule({
48
controllers: [UsersController],
49
providers: [UsersService],
50
}).compile();
51
52
controller = module.get<UsersController>(UsersController);
53
service = module.get<UsersService>(UsersService);
54
});
55
56
it("should be defined", () => {
57
expect(controller).toBeDefined();
58
});
59
});
60
```
61
62
## Architecture
63
64
NestJS Testing is built around several key components:
65
66
- **Test Class**: Entry point for creating testing modules with static `createTestingModule` method
67
- **TestingModuleBuilder**: Builder pattern for configuring test environments with provider overrides
68
- **TestingModule**: Compiled test module providing dependency injection and application creation
69
- **Override System**: Flexible system to replace providers, guards, pipes, filters, interceptors, and modules
70
- **Mock Integration**: Support for global mock factories and automatic dependency mocking
71
- **Logging Configuration**: Custom logger setup for test environments
72
73
## Capabilities
74
75
### Module Building
76
77
Core functionality for creating isolated test modules with dependency injection. Essential for unit and integration testing of NestJS components.
78
79
```typescript { .api }
80
class Test {
81
static createTestingModule(
82
metadata: ModuleMetadata,
83
options?: TestingModuleOptions
84
): TestingModuleBuilder;
85
}
86
87
interface TestingModuleOptions {
88
moduleIdGeneratorAlgorithm?: "uuid" | "timestamp";
89
}
90
```
91
92
[Module Building](./module-building.md)
93
94
### Provider Overriding
95
96
System for replacing providers, guards, pipes, filters, and interceptors with test doubles. Enables precise control over dependencies during testing.
97
98
```typescript { .api }
99
interface OverrideBy {
100
useValue(value: any): TestingModuleBuilder;
101
useFactory(options: OverrideByFactoryOptions): TestingModuleBuilder;
102
useClass(metatype: any): TestingModuleBuilder;
103
}
104
105
interface OverrideByFactoryOptions {
106
factory: (...args: any[]) => any;
107
inject?: any[];
108
}
109
```
110
111
[Provider Overriding](./provider-overriding.md)
112
113
### Module Overriding
114
115
Capability to replace entire modules with alternative implementations for testing scenarios with complex module dependencies.
116
117
```typescript { .api }
118
interface OverrideModule {
119
useModule(newModule: ModuleDefinition): TestingModuleBuilder;
120
}
121
```
122
123
[Module Overriding](./module-overriding.md)
124
125
### Mock Integration
126
127
Global mocking system with automatic fallback for unresolved dependencies. Integrates with popular mocking libraries for comprehensive test isolation.
128
129
```typescript { .api }
130
type MockFactory = (token?: InjectionToken) => any;
131
132
class TestingModuleBuilder {
133
useMocker(mocker: MockFactory): TestingModuleBuilder;
134
}
135
```
136
137
[Mock Integration](./mock-integration.md)
138
139
### Application Testing
140
141
Create full NestJS applications and microservices from test modules for end-to-end testing scenarios.
142
143
```typescript { .api }
144
class TestingModule extends NestApplicationContext {
145
createNestApplication<T extends INestApplication = INestApplication>(
146
httpAdapter?: HttpServer | AbstractHttpAdapter,
147
options?: NestApplicationOptions
148
): T;
149
createNestMicroservice<T extends object>(
150
options: NestMicroserviceOptions & T
151
): INestMicroservice;
152
}
153
```
154
155
[Application Testing](./application-testing.md)
156
157
## Types
158
159
### Core Types
160
161
```typescript { .api }
162
import {
163
ModuleMetadata,
164
NestApplicationContextOptions,
165
InjectionToken,
166
INestApplication,
167
INestMicroservice,
168
HttpServer,
169
NestApplicationOptions,
170
LoggerService,
171
} from "@nestjs/common";
172
import { AbstractHttpAdapter } from "@nestjs/core";
173
import { ModuleDefinition } from "@nestjs/core";
174
import { NestMicroserviceOptions } from "@nestjs/common/interfaces/microservices/nest-microservice-options.interface";
175
176
type TestingModuleOptions = Pick<
177
NestApplicationContextOptions,
178
"moduleIdGeneratorAlgorithm"
179
>;
180
181
type MockFactory = (token?: InjectionToken) => any;
182
183
interface OverrideBy {
184
useValue(value: any): TestingModuleBuilder;
185
useFactory(options: OverrideByFactoryOptions): TestingModuleBuilder;
186
useClass(metatype: any): TestingModuleBuilder;
187
}
188
189
interface OverrideByFactoryOptions {
190
factory: (...args: any[]) => any;
191
inject?: any[];
192
}
193
194
interface OverrideModule {
195
useModule(newModule: ModuleDefinition): TestingModuleBuilder;
196
}
197
```