NestJS E2E测试随机出现Redis与MongoDB连接失败问题求助
解决NestJS E2E测试中Mongo连接池/会话错误的方案
核心原因
Jest默认并行执行多个测试套件,当某个套件执行afterAll关闭应用(连带关闭Mongo连接池)时,其他正在运行的套件可能还在尝试使用已关闭的连接池或会话,从而触发这类随机错误。
具体修复步骤
1. 强制Jest串行执行测试套件
在jest-e2e.json配置文件中添加maxWorkers: 1,避免多套件共享连接资源:
{ "moduleFileExtensions": ["js", "json", "ts"], "rootDir": ".", "testEnvironment": "node", "testRegex": ".e2e-spec.ts$", "transform": { "^.+\\.(t|j)s$": "ts-jest" }, "maxWorkers": 1 }
2. 为每个测试套件独立管理应用实例
若需保持并行测试以提升速度,确保每个测试套件单独初始化和销毁应用,不共享实例:
describe('XX模块测试', () => { let app: INestApplication; beforeAll(async () => { const moduleFixture = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleFixture.createNestApplication(); app.useGlobalPipes( new CustomValidationPipe({ transform: true, whitelist: true, validateCustomDecorators: true, }), ); await app.init(); }); afterAll(async () => { // 显式关闭Mongo连接池(针对nest-mongodb) const mongoConnection = app.get(MongoConnection); await mongoConnection.close(); await app.close(); }); // 测试用例... });
3. 手动管理Mongo会话生命周期
在涉及数据库操作的测试中,显式创建和销毁会话,避免依赖全局过期会话:
it('测试数据库操作', async () => { const mongoConnection = app.get(MongoConnection); const session = await mongoConnection.startSession(); try { await session.withTransaction(async () => { // 你的测试逻辑 }); } finally { await session.endSession(); } });
4. 同步清理Redis连接(针对@liaoliaots/nestjs-redis)
避免Redis连接泄漏影响测试环境,在afterAll中主动关闭Redis客户端:
afterAll(async () => { const redisService = app.get(RedisService); await redisService.getClient().quit(); await app.close(); });
验证方案
修改配置或代码后,重新执行npm run test:e2e,观察是否再出现连接池关闭或会话过期的错误。
内容的提问来源于stack exchange,提问作者Amir Jani
相关产品推荐
相关产品推荐

