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

GitHub Actions CI/CD中MongoDB URI未定义及测试失败问题排查

GitHub Actions CI/CD连接MongoDB及测试失败问题

初始问题:GitHub Actions中MongoDB URI未定义

本地环境连接MongoDB正常,但在GitHub Actions运行测试时抛出错误:

Error connecting to MongoDB: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined".

已执行的调试步骤

  • 确认GitHub Secrets中环境变量配置正确,本地用.env配合dotenv-flow加载变量正常
  • 尝试在代码中硬编码MongoDB URI,错误仍存在
  • 在GitHub Actions工作流中添加步骤打印MongoDB URI,结果仍为undefined

相关代码片段

server.ts(MongoDB连接处理)

import mongoose from 'mongoose';

// Log the MongoDB URI to check if it is being set correctly
console.log("MongoDB Connection String (from env):", process.env.DBHOST);

// Temporary hardcoded URI for debugging purposes
const hardcodedUri = "your-hardcoded-mongodb-uri";
console.log("Using hardcoded MongoDB URI:", hardcodedUri);

// Use the hardcoded URI for debugging, replace `process.env.DBHOST` with `hardcodedUri` if needed
mongoose.connect(hardcodedUri, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log("Connected to MongoDB successfully"))
  .catch((error) => console.error("Error connecting to MongoDB:", error));

另一段server.ts代码:

// Connect to MongoDB using Mongoose
mongoose.set("strictQuery", false);
mongoose
  .connect(process.env.DBHOST as string)
  .catch((error) => console.log("Error connecting to MongoDB:" + error));

GitHub Actions main.yml相关部分

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      - name: Use Node.JS ${{ matrix.node-version }}
        uses: actions/setup-node@v3
        with:
          node-version: ${{ matrix.node-version }}
      - name: Install dependencies
        run: |
          cd backend
          npm install
        env:
          DBHOST: ${{ secrets.DBHOST }}
      - name: Log MongoDB URI
        run: |
          echo "MongoDB URI: $DBHOST" # Log the MongoDB URI to ensure it is set
      - name: Run tests
        run: |
          cd backend
          npx mocha --config .mocharc.json

.mocharc.json

{
  "diff": true,
  "extension": ["ts"],
  "ignore": ["test/ignore/**"],
  "package": "./package.json",
  "reporter": "spec",
  "slow": 75,
  "timeout": 5000,
  "ui": "bdd",
  "spec": "src/test/**/*.test.ts",
  "require": "ts-node/register",
  "watch-files": ["src/lib/**/*.ts", "src/test/**/*.ts"],
  "watch-ignore": ["lib/vendor"]
}

环境配置

  • Node.js: v20.x
  • Mongoose: ^6.1.7
  • dotenv-flow: ^4.1.0
  • GitHub Actions: Runner on ubuntu-latest

已尝试操作

  • 验证本地与GitHub Secrets中的环境变量一致
  • 硬编码MongoDB URI测试
  • 在CI流水线中打印URI确认是否已设置

注:近期刚切换到TypeScript,之前用JavaScript时无此问题


更新:URI未定义问题解决,但测试用例失败

按建议仅在测试步骤中引入.env变量后,URI未定义问题已解决,但测试执行卡顿,且两个测试用例失败(本地测试全部通过)。

Actions日志

> cross-env NODE_ENV=test mocha --require ts-node/register
[dotenv-flow@4.1.0]: ".env*" files loading failed: no ".env*" files matching pattern ".env[.test][.local]" in "/home/runner/work/slavic.media-2.0/slavic.media-2.0/backend" dir undefined
[dotenv-flow@4.1.0]: ".env*" files loading failed: no ".env*" files matching pattern ".env[.test][.local]" in "/home/runner/work/slavic.media-2.0/slavic.media-2.0/backend" dir undefined
Server is running on port: 4000
  Document workflow tests
Connected successfully to MongoDB
    1) should register + login a user, create document and verify 1 in DB
    2) should register + login a user, create document and delete it from DB
    ✔ Invalid user input test
  1 passing (2s)
  2 failing
  1) Document workflow tests
       should register + login a user, create document and verify 1 in DB:
      Uncaught AssertionError: expected 400 to equal 201
      + expected - actual
      -400
      +201
      
      at fn (src/test/workflow.test.ts:64:42)
      at Test.callback (node_modules/superagent/src/node/index.js:913:12)
      at fn (node_modules/superagent/src/node/index.js:1166:18)
      at IncomingMessage.<anonymous> (node_modules/superagent/src/node/parsers/json.js:19:7)
      at IncomingMessage.emit (node:events:531:35)
      at IncomingMessage.emit (node:domain:488:12)
      at endReadableNT (node:internal/streams/readable:1696:12)
      at processTicksAndRejections (node:internal/process/task_queues:82:21)
  2) Document workflow tests
       should register + login a user, create document and delete it from DB:
      Uncaught AssertionError: expected 400 to equal 201
      + expected - actual
      -400
      +201
      
      at fn (src/test/workflow.test.ts:145:42)
      at Test.callback (node_modules/superagent/src/node/index.js:913:12)
      at fn (node_modules/superagent/src/node/index.js:1166:18)
      at IncomingMessage.<anonymous> (node_modules/superagent/src/node/parsers/json.js:19:7)
      at IncomingMessage.emit (node:events:531:35)
      at IncomingMessage.emit (node:domain:488:12)
      at endReadableNT (node:internal/streams/readable:1696:12)
      at processTicksAndRejections (node:internal/process/task_queues:82:21)

排查建议

  1. 环境变量传递完整性:虽然URI已加载,但检查其他依赖的环境变量(如JWT密钥、端口等)是否在GitHub Actions的测试步骤中正确传递,测试用例返回400可能是缺少某些配置导致请求参数验证失败。
  2. dotenv-flow配置:日志提示找不到.env.test或.env.test.local文件,可在项目中添加空的.env.test文件避免加载错误,或在代码中处理dotenv-flow加载失败的情况,防止影响后续逻辑。
  3. 测试数据库状态:确认CI中使用的MongoDB数据库是干净的(无残留测试数据),本地测试可能依赖已有数据状态,而CI中每次都是全新环境,导致测试逻辑冲突。
  4. 测试超时设置:测试执行卡顿可尝试延长.mocharc.json中的timeout值(比如改为10000),避免因网络或数据库响应慢导致测试失败。
  5. 请求参数一致性:对比本地和CI中测试请求的参数,检查是否因环境差异导致参数格式或内容不同,触发后端400错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 13:00:54