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

添加firebase-admin后NestJS项目Jest测试本地通过但CI/CD失败

解决NestJS中firebase-admin导致CI/CD Jest测试失败(意外令牌'?')

问题根源

报错里的??是空值合并运算符,属于ES2020语法。本地测试通过但CI失败,通常是两个核心原因:

  • CI环境的Node.js版本低于14.x(Node.js 14及以上才原生支持??运算符)
  • Jest默认不转译node_modules内的代码,firebase-admin的未转译ES语法在CI环境中无法被Jest识别

解决方案

1. 锁定CI环境的Node.js版本

在CI配置文件(比如GitHub Actions的.github/workflows/test.yml、GitLab CI的.gitlab-ci.yml)中指定Node.js版本为14.x或更高,示例:

# GitHub Actions 配置示例
steps:
  - uses: actions/checkout@v4
  - uses: actions/setup-node@v4
    with:
      node-version: '18.x'
      cache: 'npm'
  - run: npm install
  - run: npm run test

2. 配置Jest转译firebase-admin

修改jest.config.js,调整transformIgnorePatterns规则,让Jest转译firebase-admin的代码:

module.exports = {
  moduleFileExtensions: ['js', 'json', 'ts'],
  rootDir: 'src',
  testRegex: '.*\\.spec\\.ts$',
  transform: {
    '^.+\\.(t|j)s$': 'ts-jest',
  },
  // 关键配置:排除firebase-admin,让ts-jest处理它的ES语法
  transformIgnorePatterns: [
    'node_modules/(?!(firebase-admin)/)',
  ],
  collectCoverageFrom: ['**/*.(t|j)s'],
  coverageDirectory: '../coverage',
  testEnvironment: 'node',
};

3. 检查TypeScript编译目标

确保tsconfig.json的target设置为ES2020或更高,避免编译后残留未兼容的语法:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["ES2020"],
    // 其他配置...
  }
}

4. 清理CI环境缓存

在CI脚本中添加缓存清理步骤,避免旧依赖或Jest缓存干扰测试:

npm ci
npx jest --clearCache
npm run test

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:05:21