Jest中TypeORM createConnection调用无限挂起问题求助
解决Jest中TypeORM createConnection无限挂起的问题
针对你在Jest的beforeAll钩子中调用TypeORM的createConnection时出现无限挂起的问题,结合你的代码和场景,提供以下几个排查和解决方向:
1. 调整Jest异步超时时间
Jest默认的异步操作超时为5000ms,若数据库连接耗时超过这个时间,可能导致Jest等待过程中出现看似挂起的情况。你可以:
- 在
beforeAll中手动指定更长的超时时间:
beforeAll(async () => { conn = await createConnection({ // 你的连接配置 }); }, 10000); // 设置为10秒超时
- 或者在
jest.config.ts中全局设置超时:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', testTimeout: 10000, };
2. 切换为TypeORM 0.3+的DataSource API(若使用新版本)
TypeORM 0.3.x及以上版本已弃用createConnection,改用DataSource类,旧API在测试环境下可能存在兼容性问题。修改代码如下:
import { DataSource } from "typeorm"; let dataSource: DataSource; describe('GET /healthz', () => { beforeAll(async () => { dataSource = new DataSource({ name: 'test-connection', // 使用唯一连接名 type: 'postgres', host: 'localhost', port: 5433, database: 'test-local', username: 'user', password: 'pwd', synchronize: true, logging: ['error'], // 仅记录错误日志,减少输出干扰 }); await dataSource.initialize(); }); afterAll(async () => { await dataSource.destroy(); }); it('should be true', () => { expect(true).toBe(true); }); });
3. 禁用并行测试,强制串行执行
Jest默认会并行运行测试,可能导致数据库连接资源竞争或事件循环阻塞。尝试添加--runInBand参数执行测试:
jest --runInBand --detectOpenHandles
4. 检查并调整日志输出
你当前设置了logging: true,大量日志输出可能在Jest环境下阻塞事件循环。尝试将日志级别改为仅记录错误:
createConnection({ // ...其他配置 logging: ['error'], })
5. 确认PostgreSQL驱动依赖的完整性
虽然你在常规应用中连接正常,但测试环境下可能存在依赖缺失或版本兼容问题。重新安装pg和typeorm依赖:
npm uninstall pg typeorm npm install pg typeorm
6. 排查事件循环阻塞
在createConnection前后添加事件循环检查,确认是否有同步操作阻塞:
beforeAll(async () => { console.log('Before connection, event loop active:', process._getActiveHandles().length); conn = await createConnection({ // 你的配置 }); console.log('After connection, event loop active:', process._getActiveHandles().length); });
如果日志没有输出,说明连接操作根本没有进入事件循环执行,可能需要检查TypeORM模块是否被正确加载。
内容的提问来源于stack exchange,提问作者JC97
相关产品推荐
相关产品推荐

