-
-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
scanner.spec.ts
489 lines (434 loc) 路 16.2 KB
/
scanner.spec.ts
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
import { Catch, Injectable, Logger } from '@nestjs/common';
import { expect } from 'chai';
import * as sinon from 'sinon';
import { GUARDS_METADATA } from '../../common/constants';
import { Controller } from '../../common/decorators/core/controller.decorator';
import { UseGuards } from '../../common/decorators/core/use-guards.decorator';
import { Module } from '../../common/decorators/modules/module.decorator';
import { Scope } from '../../common/interfaces';
import { ApplicationConfig } from '../application-config';
import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '../constants';
import { InvalidModuleException } from '../errors/exceptions/invalid-module.exception';
import { InvalidClassModuleException } from '../errors/exceptions/invalid-class-module.exception';
import { UndefinedModuleException } from '../errors/exceptions/undefined-module.exception';
import { NestContainer } from '../injector/container';
import { InstanceWrapper } from '../injector/instance-wrapper';
import { MetadataScanner } from '../metadata-scanner';
import { DependenciesScanner } from '../scanner';
describe('DependenciesScanner', () => {
class Guard {}
@Injectable()
class TestComponent {}
@Catch()
class TestExceptionFilterWithoutInjectable {}
@Controller('')
class TestController {}
@Module({
providers: [TestComponent],
controllers: [TestController],
exports: [TestComponent],
})
class BasicModule {}
@Module({
imports: [BasicModule],
providers: [TestComponent],
controllers: [TestController],
})
class TestModule {}
@Module({
imports: [undefined],
})
class UndefinedModule {}
@Module({
imports: [null],
})
class InvalidModule {}
let scanner: DependenciesScanner;
let mockContainer: sinon.SinonMock;
let container: NestContainer;
beforeEach(() => {
container = new NestContainer();
mockContainer = sinon.mock(container);
scanner = new DependenciesScanner(
container,
new MetadataScanner(),
new ApplicationConfig(),
);
sinon.stub(scanner, 'registerCoreModule').callsFake(async () => {});
});
afterEach(() => {
mockContainer.restore();
});
it('should "insertModule" call twice (2 modules) container method "addModule"', async () => {
const expectation = mockContainer.expects('addModule').twice();
await scanner.scan(TestModule as any);
expectation.verify();
});
it('should "insertProvider" call twice (2 components) container method "addProvider"', async () => {
const expectation = mockContainer.expects('addProvider').twice();
const stub = sinon.stub(scanner, 'insertExportedProvider');
await scanner.scan(TestModule as any);
expectation.verify();
stub.restore();
});
it('should "insertController" call twice (2 components) container method "addController"', async () => {
const expectation = mockContainer.expects('addController').twice();
await scanner.scan(TestModule as any);
expectation.verify();
});
it('should "insertExportedProvider" call once (1 component) container method "addExportedProvider"', async () => {
const expectation = mockContainer.expects('addExportedProvider').once();
await scanner.scan(TestModule as any);
expectation.verify();
});
describe('reflectDynamicMetadata', () => {
describe('when param has prototype', () => {
it('should call "reflectParamInjectables" and "reflectInjectables"', () => {
const reflectInjectables = sinon
.stub(scanner, 'reflectInjectables')
.callsFake(() => undefined);
const reflectParamInjectables = sinon
.stub(scanner, 'reflectParamInjectables')
.callsFake(() => undefined);
scanner.reflectDynamicMetadata({ prototype: true } as any, '');
expect(reflectInjectables.called).to.be.true;
expect(reflectParamInjectables.called).to.be.true;
});
});
describe('when param has not prototype', () => {
it('should not call ""reflectParamInjectables" and "reflectInjectables"', () => {
const reflectInjectables = sinon
.stub(scanner, 'reflectInjectables')
.callsFake(() => undefined);
const reflectParamInjectables = sinon
.stub(scanner, 'reflectParamInjectables')
.callsFake(() => undefined);
scanner.reflectDynamicMetadata({} as any, '');
expect(reflectInjectables.called).to.be.false;
expect(reflectParamInjectables.called).to.be.false;
});
});
});
describe('insertInjectable', () => {
it('should call "addInjectable"', () => {
const addInjectable = sinon
.stub((scanner as any).container, 'addInjectable')
.callsFake(() => undefined);
const comp = {};
const token = 'token';
scanner.insertInjectable(comp as any, token, null);
expect(addInjectable.calledWith(comp, token)).to.be.true;
});
});
class CompMethod {
@UseGuards(Guard)
public method() {}
}
describe('reflectKeyMetadata', () => {
it('should return undefined', () => {
const result = scanner.reflectKeyMetadata(TestComponent, 'key', 'method');
expect(result).to.be.undefined;
});
it('should return array', () => {
const result = scanner.reflectKeyMetadata(
CompMethod,
GUARDS_METADATA,
'method',
);
expect(result).to.be.eql([Guard]);
});
});
describe('insertModule', () => {
it('should call forwardRef() when forwardRef property exists', () => {
sinon.stub(container, 'addModule').returns({} as any);
const module = { forwardRef: sinon.spy() };
scanner.insertModule(module, []);
expect(module.forwardRef.called).to.be.true;
});
it('should throw "InvalidClassModuleException" exception when suppling a class annotated with `@Injectable()` decorator', () => {
sinon.stub(container, 'addModule').returns({} as any);
expect(scanner.insertModule(TestComponent, [])).to.be.rejectedWith(
InvalidClassModuleException,
);
});
it('should throw "InvalidClassModuleException" exception when suppling a class annotated with `@Controller()` decorator', () => {
sinon.stub(container, 'addModule').returns({} as any);
expect(scanner.insertModule(TestController, [])).to.be.rejectedWith(
InvalidClassModuleException,
);
});
it('should throw "InvalidClassModuleException" exception when suppling a class annotated with (only) `@Catch()` decorator', () => {
sinon.stub(container, 'addModule').returns({} as any);
expect(
scanner.insertModule(TestExceptionFilterWithoutInjectable, []),
).to.be.rejectedWith(InvalidClassModuleException);
});
});
describe('insertImport', () => {
it('should call forwardRef() when forwardRef property exists', async () => {
const module = { forwardRef: sinon.stub().returns({}) };
sinon.stub(container, 'addImport').returns({} as any);
await scanner.insertImport(module as any, [] as any, 'test');
expect(module.forwardRef.called).to.be.true;
});
describe('when "related" is nil', () => {
it('should throw exception', async () => {
let error;
try {
await scanner.insertImport(undefined, [] as any, 'test');
} catch (e) {
error = e;
}
expect(error).to.not.be.undefined;
});
});
});
describe('insertProvider', () => {
const token = 'token';
describe('when provider is not custom', () => {
it('should call container "addProvider" with expected args', () => {
const provider = {};
const expectation = mockContainer
.expects('addProvider')
.withArgs(provider, token);
mockContainer.expects('addProvider').callsFake(() => false);
scanner.insertProvider(provider as any, token);
expectation.verify();
});
});
describe('when provider is custom', () => {
describe('and is global', () => {
const provider = {
provide: APP_INTERCEPTOR,
useValue: true,
};
it('should call container "addProvider" with expected args', () => {
const expectation = mockContainer.expects('addProvider').atLeast(1);
mockContainer.expects('addProvider').callsFake(() => false);
scanner.insertProvider(provider, token);
expectation.verify();
});
it('should push new object to "applicationProvidersApplyMap" array', () => {
mockContainer.expects('addProvider').callsFake(() => false);
scanner.insertProvider(provider, token);
const applyMap = (scanner as any).applicationProvidersApplyMap;
expect(applyMap).to.have.length(1);
expect(applyMap[0].moduleKey).to.be.eql(token);
});
});
describe('and is global and request/transient scoped', () => {
const provider = {
provide: APP_INTERCEPTOR,
useValue: true,
scope: Scope.REQUEST,
};
it('should call container "addInjectable" with expected args', () => {
const expectation = mockContainer.expects('addInjectable').atLeast(1);
mockContainer.expects('addInjectable').callsFake(() => false);
scanner.insertProvider(provider, token);
expectation.verify();
});
});
describe('and is not global', () => {
const component = {
provide: 'CUSTOM',
useValue: true,
};
it('should call container "addProvider" with expected args', () => {
const expectation = mockContainer
.expects('addProvider')
.withArgs(component, token);
mockContainer.expects('addProvider').callsFake(() => false);
scanner.insertProvider(component, token);
expectation.verify();
});
it('should not push new object to "applicationProvidersApplyMap" array', () => {
expect((scanner as any).applicationProvidersApplyMap).to.have.length(
0,
);
mockContainer.expects('addProvider').callsFake(() => false);
scanner.insertProvider(component, token);
expect((scanner as any).applicationProvidersApplyMap).to.have.length(
0,
);
});
});
});
});
describe('applyApplicationProviders', () => {
it('should apply each provider', () => {
const provider = {
moduleKey: 'moduleToken',
providerKey: 'providerToken',
type: APP_GUARD,
};
(scanner as any).applicationProvidersApplyMap = [provider];
const expectedInstance = {};
mockContainer.expects('getModules').callsFake(() => ({
get: () => ({
providers: { get: () => ({ instance: expectedInstance }) },
}),
}));
const applySpy = sinon.spy();
sinon.stub(scanner, 'getApplyProvidersMap').callsFake(() => ({
[provider.type]: applySpy,
}));
scanner.applyApplicationProviders();
expect(applySpy.called).to.be.true;
expect(applySpy.calledWith(expectedInstance)).to.be.true;
});
it('should apply each globally scoped provider', () => {
const provider = {
moduleKey: 'moduleToken',
providerKey: 'providerToken',
type: APP_GUARD,
scope: Scope.REQUEST,
};
(scanner as any).applicationProvidersApplyMap = [provider];
const expectedInstanceWrapper = new InstanceWrapper();
mockContainer.expects('getModules').callsFake(() => ({
get: () => ({
injectables: { get: () => expectedInstanceWrapper },
}),
}));
const applySpy = sinon.spy();
sinon.stub(scanner, 'getApplyRequestProvidersMap').callsFake(() => ({
[provider.type]: applySpy,
}));
scanner.applyApplicationProviders();
expect(applySpy.called).to.be.true;
expect(applySpy.calledWith(expectedInstanceWrapper)).to.be.true;
});
});
describe('addScopedEnhancersMetadata', () => {
const provider = {
moduleKey: 'moduleToken',
providerKey: 'providerToken',
type: APP_GUARD,
scope: Scope.REQUEST,
};
it('should add enhancers metadata to every controller', () => {
(scanner as any).applicationProvidersApplyMap = [provider];
const instance = new InstanceWrapper({ name: 'test' });
const controllers = new Map();
const mockController = new InstanceWrapper();
controllers.set('test', mockController);
mockContainer.expects('getModules').callsFake(() => ({
get: () => ({
injectables: { get: () => instance },
controllers,
}),
values() {
return [this.get()];
},
}));
const addEnhancerMetadataSpy = sinon.spy(
mockController,
'addEnhancerMetadata',
);
scanner.addScopedEnhancersMetadata();
expect(addEnhancerMetadataSpy.called).to.be.true;
expect(addEnhancerMetadataSpy.calledWith(instance)).to.be.true;
});
});
describe('getApplyProvidersMap', () => {
describe(`when token is ${APP_INTERCEPTOR}`, () => {
it('call "addGlobalInterceptor"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig,
'addGlobalInterceptor',
);
scanner.getApplyProvidersMap()[APP_INTERCEPTOR](null);
expect(addSpy.called).to.be.true;
});
});
describe(`when token is ${APP_GUARD}`, () => {
it('call "addGlobalGuard"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig,
'addGlobalGuard',
);
scanner.getApplyProvidersMap()[APP_GUARD](null);
expect(addSpy.called).to.be.true;
});
});
describe(`when token is ${APP_PIPE}`, () => {
it('call "addGlobalPipe"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig,
'addGlobalPipe',
);
scanner.getApplyProvidersMap()[APP_PIPE](null);
expect(addSpy.called).to.be.true;
});
});
describe(`when token is ${APP_FILTER}`, () => {
it('call "addGlobalFilter"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig,
'addGlobalFilter',
);
scanner.getApplyProvidersMap()[APP_FILTER](null);
expect(addSpy.called).to.be.true;
});
});
});
describe('getApplyRequestProvidersMap', () => {
describe(`when token is ${APP_INTERCEPTOR}`, () => {
it('call "addGlobalRequestInterceptor"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig,
'addGlobalRequestInterceptor',
);
scanner.getApplyRequestProvidersMap()[APP_INTERCEPTOR](null);
expect(addSpy.called).to.be.true;
});
});
describe(`when token is ${APP_GUARD}`, () => {
it('call "addGlobalRequestGuard"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig,
'addGlobalRequestGuard',
);
scanner.getApplyRequestProvidersMap()[APP_GUARD](null);
expect(addSpy.called).to.be.true;
});
});
describe(`when token is ${APP_PIPE}`, () => {
it('call "addGlobalRequestPipe"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig,
'addGlobalRequestPipe',
);
scanner.getApplyRequestProvidersMap()[APP_PIPE](null);
expect(addSpy.called).to.be.true;
});
});
describe(`when token is ${APP_FILTER}`, () => {
it('call "addGlobalRequestFilter"', () => {
const addSpy = sinon.spy(
(scanner as any).applicationConfig,
'addGlobalRequestFilter',
);
scanner.getApplyRequestProvidersMap()[APP_FILTER](null);
expect(addSpy.called).to.be.true;
});
});
});
describe('scanForModules', () => {
it('should throw an exception when the imports array includes undefined', () => {
try {
scanner.scanForModules(UndefinedModule, [UndefinedModule]);
} catch (exception) {
expect(exception instanceof UndefinedModuleException).to.be.true;
}
});
it('should throw an exception when the imports array includes an invalid value', () => {
try {
scanner.scanForModules(InvalidModule, [InvalidModule]);
} catch (exception) {
expect(exception instanceof InvalidModuleException).to.be.true;
}
});
});
});