I need help with implementing a custom CacheModule in NestJS. The guide only shows how to connect the cache directly to the main module of the AppModule application. What is the correct way to define and implement a custom cache module?
My attempt at creating a custom cache module has not been successful. When I try to add it as a dependency to the test module, the tests do not run because they cannot access the custom cache module.
This is my custom.cache.module.ts file:
@Module({})
export class CustomCacheModule {
static forRoot(): DynamicModule {
return {
imports: [CacheModule.register({ isGlobal: true })],
module: CustomCacheModule,
providers: [
{ useClass: CacheService, provide: CACHE_SERVICE },
{ useClass: CalculatorService, provide: CALCULATOR_SERVICE },
{
useClass: ExpressionCounterService,
provide: EXPRESSION_COUNTER_SERVICE,
},
{
useClass: RegExCreatorService,
provide: REGEXP_CREATOR_SERVICE_INTERFACE,
},
],
exports: [CustomCacheModule],
};
}
}
The import statement in my AppModule requires me to call the forRoot method, which I find inconvenient but necessary based on existing implementations.
Here is an excerpt from my app.module.ts file:
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
CustomCacheModule.forRoot(),
DBModule,
HistoryModule,
CalculatorModule,
],
})
export class AppModule {}
In an effort to follow best practices, I have included my spec file below. Despite setting up all dependencies, the code in the spec file does not work. Can you spot any errors or suggest improvements?
This is my calculator.controller.spec.ts file:
let calculatorController: CalculatorController;
let calculatorService: CalculatorService;
afterAll((done) => {
mongoose.connection.close();
done();
});
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
imports: [HistoryModule, CustomCacheModule],
controllers: [CalculatorController],
providers: [
CalculatorService,
{
provide: CacheService,
useValue: {
checkInCache: jest.fn().mockReturnValue(Promise<null>),
setToCache: jest.fn().mockReturnValue(Promise),
},
},
],
})
.useMocker(() => createMock())
.compile();
calculatorController =
moduleRef.get<CalculatorController>(CalculatorController);
calculatorService = moduleRef.get<CalculatorService>(CalculatorService);
jest.clearAllMocks();
});
describe('Calculator Controller', () => {
it('should be defined', () => {
expect(calculatorController).toBeDefined();
});
it('should have all methods', () => {
expect(calculatorController.getResult).toBeDefined();
expect(calculatorController.getResult(calculatorStub().request)).toBe(
typeof Promise,
);
});
});