You need to enable JavaScript to run this app. NestJS应用Jest E2E测试在CircleCI运行超时无法退出问题排查
优惠活动
大模型
产品
解决方案
定价
更多

NestJS应用Jest E2E测试在CircleCI运行超时无法退出问题排查

问题场景
  • 基于NestJS开发的应用,配套实现了基于Jest的端到端(E2E)测试套件
  • 本地环境运行整套测试仅需13秒左右,全流程无异常
  • 在CircleCI流水线环境执行时,最初的表现为测试进程无故挂起、无法正常退出,最终触发10分钟超时导致流水线失败,无明确报错可定位问题根因
  • 移除测试执行命令中的--inspect-brk参数后,完整运行报错暴露:
    • 测试用例触发30000ms超时
    • 测试实例app未初始化完成时,抛出Cannot read property 'getHttpServer' of undefined错误
    • 测试执行完成后数据库连接未被正常关闭,日志中出现Nest框架重复重试连接数据库的记录
    • Jest检测到存在未释放的异步句柄,提示需运行--detectOpenHandles排查问题,进程持续挂起直到触发超时
  • 上述所有异常均仅在CircleCI流水线环境复现,本地环境运行整套测试无任何问题
核心配置与实现逻辑

CircleCI流水线配置

配置文件位于项目路径/.circleci/config.yml,核心内容如下:

version: 2.1
jobs:
  run_tests:
    docker:
      - image: circleci/node:10
    steps:
      - checkout #cloning git repo
      - run:
          name: Install npm dependencies
          command: |
            npm install --save
      - run:
          name: Run unit tests
          command: |
            NODE_ENV=test && node node_modules/.bin/jest
          environment:
            DATABASE_URL: postgres://_:_:@localhost:5432/testdb
      - run:
          name: Run e2e tests
          command: |
            NODE_ENV=test && node --inspect-brk node_modules/.bin/jest --runInBand --config ./test/jest-e2e.json --watchAll=false
          environment:
            DATABASE_URL: postgres://_:_:@localhost:5432/testdb
      - store_test_results:
          path: test-results
workflows:
  build_test:
    jobs:
      - run_tests

Jest E2E测试配置

配置文件位于项目路径test/jest-e2e.json,核心内容如下:

{
  "moduleFileExtensions": ["js", "json", "ts"],
  "rootDir": ".",
  "testEnvironment": "node",
  "testRegex": ".e2e-spec.ts$",
  "transform": {
    "^.+\\.(t|j)s$": "ts-jest"
  },
  "verbose": true
}

测试生命周期逻辑

测试用例的核心生命周期实现代码如下:

beforeAll(async () => {
    const rootModule: TestingModule = await Test.createTestingModule({
      imports: [RootModule]
    }).compile();

    app = rootModule.createNestApplication();
    await app.init();
    shopboxService = app.select(ShopboxModule).get(ShopboxService);
    clothesService = app.select(ClothesModule).get(ClothesService);
    await shopboxService.deleteTags();
  });

  it('authenticates a user and includes a jwt token in the response', async () => {
    const response = await request(app.getHttpServer())
      .post('/auth/login')
      .send({ email: 'myemail@example.com', password: '123456789' })
      .expect(201);

    adminAccessToken = response.body.token;

    expect(adminAccessToken).toMatch(
      /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/
    );
  });

  afterAll(async () => {
    try {
      await shopboxService.deleteTags();
    } catch (e) {
      console.warn('error', e);
    } finally {
      await app.close();
    }
  });

内容的提问来源于stack exchange,提问作者Jonas Grønbek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.17 00:15:10