NestJS自定义CacheModule实现及测试问题咨询
NestJS 自定义CacheModule 正确实现方案(无需调用forRoot)
问题诊断
你遇到的测试模块不识别自定义CacheModule的问题,大概率是以下原因之一:
- 自定义模块未正确导出官方CacheModule的核心Provider(比如
CacheService) - 自定义模块未完成缓存初始化配置,或者未将配置逻辑封装到模块内部
- 测试模块未正确导入自定义CacheModule,导致依赖无法注入
正确实现步骤
1. 编写自定义CacheModule
直接在模块内部完成官方CacheModule的初始化,同时导出核心依赖,可设置为全局模块避免重复导入:
// custom.cache.module.ts import { Module, Global } from '@nestjs/common'; import { CacheModule } from '@nestjs/cache-manager'; // 如果你用Redis存储,需要安装cache-manager-redis-store,内存存储可省略 import * as redisStore from 'cache-manager-redis-store'; // @Global() 可选:如果想让所有模块自动识别,加上这个装饰器 @Global() @Module({ imports: [ // 直接在内部调用register完成缓存配置,无需外部调用forRoot CacheModule.register({ store: redisStore, // 替换为你的缓存存储(内存存储可删除此配置) host: 'localhost', port: 6379, ttl: 300, // 默认缓存过期时间(秒) isGlobal: false, // 这里设为false,因为我们的自定义模块已经处理全局逻辑 }), ], // 导出官方CacheModule,确保其他模块能注入CacheService exports: [CacheModule], }) export class CustomCacheModule {}
2. 主模块集成
在AppModule中直接导入自定义模块即可,无需额外配置:
// app.module.ts import { Module } from '@nestjs/common'; import { CustomCacheModule } from './custom.cache.module'; import { CalculatorController } from './calculator.controller'; @Module({ imports: [CustomCacheModule], controllers: [CalculatorController], }) export class AppModule {}
3. 测试模块配置
测试环境是隔离的,需要在测试模块中明确导入自定义CacheModule:
// calculator.controller.spec.ts import { Test, TestingModule } from '@nestjs/testing'; import { CalculatorController } from './calculator.controller'; import { CustomCacheModule } from './custom.cache.module'; describe('CalculatorController', () => { let controller: CalculatorController; let module: TestingModule; beforeEach(async () => { module = await Test.createTestingModule({ imports: [CustomCacheModule], // 必须导入自定义缓存模块 controllers: [CalculatorController], }).compile(); controller = module.get<CalculatorController>(CalculatorController); }); it('should be defined', () => { expect(controller).toBeDefined(); }); // 可选:验证缓存服务是否可正常注入 it('should have access to CacheService', () => { const cacheService = module.get('CacheService'); expect(cacheService).toBeDefined(); }); });
关键注意点
- 无需调用
forRoot:缓存配置逻辑已经封装在CustomCacheModule内部的CacheModule.register()中,外部模块直接导入即可使用 - 全局模块可选:如果不想让模块全局生效,去掉
@Global()装饰器,在需要的业务模块中手动导入CustomCacheModule即可 - 测试必须显式导入:即使设置了全局模块,测试环境的模块是独立创建的,仍需在
Test.createTestingModule中导入自定义模块才能获取缓存依赖
内容的提问来源于stack exchange,提问作者tresor13
相关产品推荐
相关产品推荐

