You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GitLab CI中jest-mongodb测试失败 实例未就绪即退出问题求助

问题场景

使用jest-mongodb执行npm run test测试时,本地环境可正常运行,但GitLab CI流水线中原先正常的任务突然失效抛出错误。

现有jest.config.js配置

const merge = require('merge');
const ts_preset = require('ts-jest/jest-preset');
const jest_mongodb = require('@shelf/jest-mongodb/jest-preset');

module.exports = merge.recursive(ts_preset, jest_mongodb, {
  globals: {
    test_url: `http://${process.env.HOST || '127.0.0.1'}:${
      process.env.PORT || 3000
    }`,
  },
  preset: '@shelf/jest-mongodb',
  setupFiles: ['dotenv/config'],
  testPathIgnorePatterns: ['<rootDir>/__tests__/helpers'],
});

错误信息

核心错误日志:

Error: Jest: Got error running 
globalSetup - /builds/elo/elo-api/node_modules/@shelf/jest-mongodb/setup.js, 
reason: Instance Exited before 
being ready and without throwing an error!

错误参考截图:
错误截图

问题根因

该错误本质是CI环境中@shelf/jest-mongodb依赖的mongodb-memory-server实例启动失败,未在超时时间内完成就绪,常见触发原因包括:

  • 配置冲突:现有配置同时通过merge.recursive合并了jest-mongodb预设,又手动重复声明preset: '@shelf/jest-mongodb',导致预设重复加载、部分启动配置被覆盖
  • 版本兼容问题:@shelf/jest-mongodb默认拉取latest版本的MongoDB二进制,新版MongoDB可能和GitLab Runner基础镜像的系统依赖(libcurl、openssl、liblzma等)不兼容,本地环境依赖完整所以可以正常运行
  • 端口/权限问题:CI环境默认随机端口被安全策略拦截,或者root用户运行CI容器时新版MongoDB默认禁止root启动,导致进程直接退出
  • 网络问题:CI环境临时拉取MongoDB二进制时网络超时、文件损坏,导致实例无法启动
修复方案

按优先级依次验证修复:

1. 修复配置冲突,固定MongoDB版本

删除重复的preset声明,同时显式指定和本地运行一致的MongoDB版本,禁止自动拉取latest版本,修改后的jest.config.js参考:

const merge = require('merge');
const ts_preset = require('ts-jest/jest-preset');
const jest_mongodb = require('@shelf/jest-mongodb/jest-preset');

module.exports = merge.recursive(ts_preset, jest_mongodb, {
  globals: {
    test_url: `http://${process.env.HOST || '127.0.0.1'}:${
      process.env.PORT || 3000
    }`,
  },
  // 移除重复声明的preset字段,merge操作已经完成预设合并
  setupFiles: ['dotenv/config'],
  testPathIgnorePatterns: ['<rootDir>/__tests__/helpers'],
  // 显式配置内存MongoDB参数
  testEnvironmentOptions: {
    mongodbMemoryServerOptions: {
      binary: {
        version: '4.4.18', // 替换为本地运行正常的MongoDB版本,禁止使用latest
        skipMD5: true
      },
      autoStart: false,
      instance: {
        port: 27017, // 固定启动端口,避免随机端口被CI安全策略拦截
        args: ['--noauth'] // 关闭权限校验,适配root用户运行的CI环境
      }
    }
  }
});

2. 给GitLab Runner补充系统依赖

如果使用Debian/Ubuntu系的Node基础镜像,在测试执行前安装MongoDB运行必需的系统依赖,.gitlab-ci.yml参考配置:

test:
  stage: test
  image: node:16-bullseye
  before_script:
    - apt update && apt install -y --no-install-recommends libcurl4 openssl liblzma5 ca-certificates
    - npm ci
  script:
    - npm run test

3. 增加二进制缓存避免网络拉取失败

在CI配置中添加MongoDB二进制缓存目录,避免每次流水线临时拉取二进制出现网络异常:

variables:
  MONGOMS_DOWNLOAD_DIR: $CI_PROJECT_DIR/.cache/mongodb
  MONGOMS_VERSION: 4.4.18 # 和配置中指定的版本保持一致

cache:
  paths:
    - .cache/mongodb
    - node_modules

内容的提问来源于stack exchange,提问作者Abdelhadi Abdo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 23:48:21