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

如何在Node.js项目中使用Circle CI运行单元测试

问题原因

本地运行时你使用两个独立终端分别执行服务启动和测试命令,两个进程并行运行互不干扰。但CircleCI的步骤是同步串行执行的,只有当前步骤的命令进程退出后,才会执行下一个步骤。你配置的npm start是常驻前台的服务进程,不会主动终止,因此CI流程会一直卡在启动服务的步骤,无法执行后续测试。

解决方案

方案1:后台启动+等待服务就绪

将服务放到后台运行,同时增加就绪检测逻辑,确认服务启动完成后再执行测试,修改后的config.yml参考如下:

version: 2.1
jobs:
  run_tests:
    docker:
      - image: circleci/node:12
    steps:
    - checkout
    - run:
        name: Install npm dependencies
        command: |
          npm install --save
          # 安装wait-on工具用于检测服务端口是否就绪,比固定等待时间更可靠
          npm install -g wait-on
    - run:
        name: Start node server
        command: |
          # & 符号将服务进程放到后台运行
          npm start &
          # 请将3000替换为你实际的服务监听端口,等待端口可访问后再往下执行
          wait-on http://localhost:3000
    - run:
        name: Run Unit Tests
        command: |
          npm run test
workflows:
  build_test:
    jobs:
      - run_tests

方案2:使用start-server-and-test工具(更推荐)

这是专门适配「先启动服务再执行测试」场景的工具,会自动处理后台启服务、等待就绪、测试完成后自动关停服务的逻辑,适配性和稳定性更高。

  1. 先在项目中安装开发依赖:
npm install --save-dev start-server-and-test
  1. 修改package.json的scripts配置:
{
  "scripts": {
    "start": "你原有的服务启动命令",
    "test": "你原有的测试命令",
    "test:ci": "start-server-and-test start http://localhost:3000 test"
  }
}
  1. 简化CircleCI配置,将启动服务和测试合并为一个步骤:
version: 2.1
jobs:
  run_tests:
    docker:
      - image: circleci/node:12
    steps:
    - checkout
    - run:
        name: Install npm dependencies
        command: npm install
    - run:
        name: Run unit tests
        command: npm run test:ci
workflows:
  build_test:
    jobs:
      - run_tests

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 22:15:05