NestJS+Jest+TypeORM测试超时:调长时长仍报hook超时错误
NestJS E2E测试Hook超时问题
我的测试始终抛出错误:"Exceeded timeout of (当前设置的超时数值) ms for a hook"。我已尝试通过Jest的jest.setTimeout()方法将超时值调整为10000、20000甚至100000ms,但仍持续触发该错误。
错误情况
错误截图显示:测试的beforeAll钩子执行超时,超出了设置的时间阈值。
测试代码(city.e2e-spec.ts)
import * as request from 'supertest'; import { Test } from '@nestjs/testing'; import { INestApplication } from '@nestjs/common'; import { CityModule } from '@app/modules/public/city'; import { City } from '@app/entity/city/city.entity'; import { createConnections, getRepository } from 'typeorm'; import { getRepositoryToken } from '@nestjs/typeorm'; jest.useFakeTimers(); jest.setTimeout(10000); describe('City E2E', () => { let app: INestApplication; beforeAll(async () => { await createConnections(); const moduleRef = await Test.createTestingModule({ imports: [CityModule], providers: [{ provide: getRepositoryToken(City), useValue: getRepository(City) }] }).compile(); app = moduleRef.createNestApplication(); app.setGlobalPrefix('v1/public'); await app.init(); }); afterAll(async () => { await app.close(); }); it('[GET] /cities', () => { return request(app.getHttpServer()) .get('/cities') .expect(200) .expect(['array with cities...']); }); });
解决方法
移除
jest.useFakeTimers()
启用假计时器会替换原生定时器API,干扰数据库连接、应用初始化等依赖真实时间的异步逻辑,直接导致Hook超时。删除该行即可恢复正常计时。给单个Hook单独设置超时
全局jest.setTimeout()可能未覆盖到Hook,可在beforeAll内部单独设置更长超时:beforeAll(async () => { jest.setTimeout(30000); // 原有初始化代码... });也可在
describe块内直接设置,作用于整个测试块的所有Hook和用例:describe('City E2E', () => { jest.setTimeout(30000); // 原有代码... });排查TypeORM连接问题
createConnections()可能因数据库配置异常(如远程数据库延迟、连接池参数错误)导致连接缓慢。可单独测试数据库连接是否能快速建立,定位是否为数据库端问题。移除冗余的Repository提供者
CityModule已注册过City的Repository,手动重复提供会增加初始化冗余耗时,直接删除该提供者即可:const moduleRef = await Test.createTestingModule({ imports: [CityModule], // 移除该行:providers: [{ provide: getRepositoryToken(City), useValue: getRepository(City) }] }).compile();
内容的提问来源于stack exchange,提问作者Gabriel Borges
相关产品推荐
相关产品推荐

