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

NestJS项目GitLab CI执行Jest测试报Unexpected token '.'错误

解决GitLab CI中NestJS Jest测试的SyntaxError: Unexpected token '.'问题

问题重现

本地基于NestJS运行Jest基础测试用例完全正常,但GitLab CI环境执行时持续报错:

/builds/qcx/qcx-app-store-api/node_modules/jest/node_modules/jest-cli/build/run.js:129
    if (error?.stack) {
              ^
SyntaxError: Unexpected token '.'

核心原因

错误中的?.是ES2020新增的可选链操作符,该特性需要Node.js 14.0.0及以上版本支持。GitLab CI环境使用的Node.js版本低于14,无法识别该语法,导致执行失败。

解决步骤

1. 指定GitLab CI使用兼容的Node.js版本

修改.gitlab-ci.yml,将镜像替换为官方Node.js 18.x版本(与package.json中@types/node@18.15.1对应,确保版本一致):

node_modules:
  stage: build
  image: node:18
  artifacts:
    name: node_modules
    paths:
      - node_modules
  script:
    - rm -rf package-lock.json node_modules
    - npm install
  extends:
    - .defaults:test
  cache:
    key:
      files:
        - package-lock.json
    paths:
      - node_modules


test:
  stage: test
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event"'
      when: never
    - if: '$DEPLOY_ONLY == "false"'
      when: always
  script:
    - npm run test
  needs:
    - docker-image
    - node_modules
  extends:
    - .defaults:test
    - docker-image
  image: node:18

注:原node_modules阶段的script命令存在语法错误(多命令未分隔),已修正为分步执行

2. 验证Node.js版本一致性

  • 本地执行node -v确认当前使用的Node版本,确保CI环境镜像版本与本地匹配
  • 可在CI脚本中添加版本检查(可选):
    test:
      script:
        - node -v # 打印Node版本,确认是否符合要求
        - npm run test
    

3. 优化CI依赖安装(可选)

由于node_modules阶段已生成artifacts并缓存,test阶段无需重复执行npm install,直接复用缓存依赖即可减少构建时间。

验证

重新触发GitLab CI流水线,确认测试用例正常执行,不再出现SyntaxError。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 12:22:51