Performance: Testing module setup
This affects the initial load time and memory usage of test suites by controlling how modules and dependencies are instantiated.
beforeEach(async () => { await Test.createTestingModule({ providers: [MyService, { provide: DepService, useValue: mockDep }], }).compile(); });
beforeEach(async () => { await Test.createTestingModule({ imports: [AppModule], }).compile(); });
| Pattern | Modules Loaded | Memory Usage | Startup Time | Verdict |
|---|---|---|---|---|
| Import full AppModule | All modules | High | Slow | [X] Bad |
| Import only needed providers | Minimal modules | Low | Fast | [OK] Good |
Test.createTestingModule() in NestJS testing?Test.createTestingModule()compile()compile() method returns a Promise, so it must be awaited.await with Test.createTestingModule({}).compile(). Others are either missing await or use invalid methods.service.getData() return?
const moduleRef = await Test.createTestingModule({
providers: [{
provide: 'DataService',
useValue: { getData: () => 'mocked data' },
}],
}).compile();
const service = moduleRef.get('DataService');
return service.getData();getData method returns 'mocked data'.moduleRef.get('DataService') returns the mocked object, so service.getData() returns 'mocked data'.const moduleRef = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
});
const controller = moduleRef.get(AppController);
compile() to finalize it before retrieving instances.await moduleRef.compile(), so moduleRef.get() will fail or behave unexpectedly.useValue in the providers array.provide and useValue to inject the mock.useValue for the dependency in providers array -> Option APass the test and this pattern moves unknown