-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.factory.test.ts
More file actions
297 lines (259 loc) · 9.27 KB
/
app.factory.test.ts
File metadata and controls
297 lines (259 loc) · 9.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import { ValidationException } from '@douglasneuroinformatics/libjs';
import { APP_FILTER, APP_GUARD, APP_PIPE } from '@nestjs/core';
import { Test, TestingModule } from '@nestjs/testing';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { beforeAll, describe, expect, it, vi } from 'vitest';
import type { Mock } from 'vitest';
import { GlobalExceptionFilter } from '../../filters/global-exception.filter.js';
import { delay } from '../../middleware/delay.middleware.js';
import { ConfigService } from '../../modules/config/config.service.js';
import { CryptoService } from '../../modules/crypto/crypto.service.js';
import { ValidationPipe } from '../../pipes/validation.pipe.js';
import { $BaseEnv } from '../../schemas/env.schema.js';
import { AppFactory } from '../app.factory.js';
import type { PrismaModuleOptions } from '../../modules/prisma/prisma.config.js';
import type { BaseEnv } from '../../schemas/env.schema.js';
import type { CreateAppOptions } from '../app.factory.js';
vi.mock(import('../../middleware/delay.middleware.js'), async (importOriginal) => {
const { delay } = await importOriginal();
return {
delay: vi.fn(delay)
};
});
vi.mock('../../modules/crypto/crypto.service.js', async (importOriginal) => {
const { CryptoService } = await importOriginal<typeof import('../../modules/crypto/crypto.service.js')>();
return {
CryptoService: vi.fn((options: any) => new CryptoService(options))
};
});
const defaultEnv = {
API_PORT: '5500',
DEBUG: 'false',
MONGO_URI: 'mongodb://localhost:27017',
NODE_ENV: 'test',
SECRET_KEY: '2622d72669dd194b98cffd9098b0d04b',
THROTTLER_ENABLED: 'false',
VERBOSE: 'false'
} satisfies { [K in keyof BaseEnv]?: string };
const defaultAppOptions: CreateAppOptions = {
envSchema: $BaseEnv,
prisma: {
client: {
constructor: vi.fn(() => {
return {
$connect: vi.fn(),
$disconnect: vi.fn(),
$extends: vi.fn().mockReturnThis()
} as any;
})
},
dbPrefix: null
},
version: '1'
};
// Helper functions
const setupEnv = (env: typeof defaultEnv) => {
Object.entries(env).forEach(([key, value]) => {
vi.stubEnv(key, value);
});
};
const createAppContainer = (options: Partial<CreateAppOptions> = {}) => {
return AppFactory.create({
...defaultAppOptions,
...options
});
};
const createModuleRef = async (options: Partial<CreateAppOptions> = {}) => {
const appContainer = createAppContainer(options);
return Test.createTestingModule({
imports: [appContainer.module]
}).compile();
};
// Test suites
describe('AppFactory', () => {
describe('create', () => {
beforeAll(() => {
setupEnv(defaultEnv);
});
describe('basic configuration', () => {
it('should create an app with minimal options', () => {
const appContainer = createAppContainer();
expect(appContainer).toBeDefined();
expect(appContainer.module).toBeDefined();
expect(appContainer.module.imports).toContainEqual(expect.objectContaining({ module: expect.any(Function) }));
expect(appContainer.module.providers).toContainEqual(
expect.objectContaining({
provide: APP_FILTER,
useClass: GlobalExceptionFilter
})
);
expect(appContainer.module.providers).toContainEqual(
expect.objectContaining({
provide: APP_PIPE,
useClass: ValidationPipe
})
);
});
it('should create an app with custom providers', () => {
const customProvider = {
provide: 'CUSTOM_TOKEN',
useValue: 'custom value'
};
const appContainer = createAppContainer({ providers: [customProvider] });
expect(appContainer.module.providers).toContainEqual(customProvider);
});
it('should create an app with docs configuration', () => {
const docsConfig = {
description: 'Test Description',
path: '/docs' as const,
title: 'Test API'
};
const appContainer = createAppContainer({ docs: docsConfig });
expect(appContainer.docs).toEqual(docsConfig);
});
it('should create an app with a custom prisma configuration', async () => {
const prisma: PrismaModuleOptions = {
client: {
constructor: defaultAppOptions.prisma.client.constructor,
options: {
omit: {
user: {
password: true
}
}
}
},
dbPrefix: 'example'
};
await createAppContainer({ prisma }).createApplicationInstance();
expect(prisma.client.constructor).toHaveBeenLastCalledWith({
datasourceUrl: `${defaultEnv.MONGO_URI}/example-test`,
...prisma.client.options
});
});
});
describe('conditional features', () => {
it('should create an app with conditional imports', () => {
class TestModule {}
const conditionalModule = {
module: TestModule,
when: 'DEBUG' as const
};
const appContainer = createAppContainer({ imports: [conditionalModule] });
expect(appContainer.module.imports).not.toContainEqual(expect.objectContaining({ module: TestModule }));
});
it('should create an app with throttler enabled', () => {
vi.stubEnv('THROTTLER_ENABLED', 'true');
const appContainer = createAppContainer();
expect(appContainer.module.imports).toContainEqual(
expect.objectContaining({
module: ThrottlerModule
})
);
expect(appContainer.module.providers).toContainEqual(
expect.objectContaining({
provide: APP_GUARD,
useClass: ThrottlerGuard
})
);
vi.stubEnv('THROTTLER_ENABLED', defaultEnv.THROTTLER_ENABLED);
});
});
describe('error handling', () => {
it('should throw an error if it cannot parse the schema', () => {
vi.stubEnv('VERBOSE', '1');
expect(() => createAppContainer()).toThrow(
expect.objectContaining({
cause: expect.any(ValidationException),
message: 'Failed to parse environment config'
})
);
vi.stubEnv('VERBOSE', defaultEnv.VERBOSE);
});
});
describe('service configuration', () => {
describe('default configuration', () => {
let moduleRef: TestingModule;
beforeAll(async () => {
moduleRef = await createModuleRef();
});
it('should provide the ConfigService', () => {
expect(moduleRef.get(ConfigService)).toBeDefined();
});
it('should provide the CryptoService with the default number of pbkdf2 iterations', () => {
expect(moduleRef.get(CryptoService)).toBeDefined();
expect(CryptoService).toHaveBeenLastCalledWith(
expect.objectContaining({
pbkdf2Params: {
iterations: 100_000
}
})
);
});
it('should not call the delay middleware by default', () => {
expect(delay).not.toHaveBeenCalled();
});
});
describe('custom configuration', () => {
let configureMiddleware: Mock;
let moduleRef: TestingModule;
beforeAll(async () => {
vi.stubEnv('API_RESPONSE_DELAY', '10');
vi.stubEnv('DANGEROUSLY_DISABLE_PBKDF2_ITERATION', 'true');
vi.stubEnv('NODE_ENV', 'development');
configureMiddleware = vi.fn();
moduleRef = await createModuleRef({ configureMiddleware });
});
it('should provide the CryptoService with pbkdf2 iterations disabled', () => {
expect(moduleRef.get(CryptoService)).toBeDefined();
expect(CryptoService).toHaveBeenLastCalledWith(
expect.objectContaining({
pbkdf2Params: {
iterations: 1
}
})
);
});
it('should call the delay and custom middleware', async () => {
const app = moduleRef.createNestApplication();
await app.init();
expect(configureMiddleware).toHaveBeenCalledOnce();
expect(delay).toHaveBeenLastCalledWith({ responseDelay: 10 });
await app.close();
});
});
});
describe('conditional imports', () => {
let DebugModule: ReturnType<typeof vi.fn>;
let init: (debug?: boolean) => Promise<TestingModule>;
beforeAll(() => {
DebugModule = vi.fn(() => {
return {};
});
init = (debug?: boolean) => {
vi.stubEnv('DEBUG', debug?.toString() ?? '');
return createModuleRef({
imports: [
{
module: DebugModule,
when: 'DEBUG'
}
]
});
};
});
it('should not import the DebugModule if debug is undefined', async () => {
await init();
expect(DebugModule).not.toHaveBeenCalled();
});
it('should not import the DebugModule if debug is false', async () => {
await init(false);
expect(DebugModule).not.toHaveBeenCalled();
});
it('should import the DebugModule if debug is true', async () => {
await init(true);
expect(DebugModule).toHaveBeenCalledOnce();
});
});
});
});