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

如何让Nrwl Nest.js Jest工作区兼容Firebase ES6包?

问题:Nrwl Nest.js TypeScript项目中Jest兼容ES6格式Firebase依赖的解决方案

背景

我通过npx create-nx-workspace搭建了基于Nrwl的Angular-Jest应用,为实现扩展模拟器本地运行,将Firebase相关依赖版本从:

"firebase": "9.1.3",
"firebase-admin": "9.12.0",
"firebase-functions": "3.15.7",

升级到:

"firebase": "9.16.0",
"firebase-admin": "11.5.0",
"firebase-functions": "4.2.0",

应用本身可正常运行,但Jest测试时出现ES6语法兼容错误。

错误信息

● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

/Users/[justOnlyMe]/Desktop/[nrwlProject]/node_modules/firebase-admin/lib/esm/auth/index.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import mod from "../../auth/index.js";
                                                                                  ^^^^^^

SyntaxError: Cannot use import statement outside a module

  at Runtime.createScriptFromCode (../../../node_modules/jest-runtime/build/index.js:1728:14)
  at Object.<anonymous> (../../../node_modules/firebase-functions/lib/common/providers/identity.js:25:14)

已尝试的配置

我曾尝试通过transformIgnorePatterns让Jest转换Firebase相关的node_modules文件,但配置后Jest运行无响应,推测是ts-jest的问题。相关配置片段:

transform: {
    '^.+\\.[tj]s$': 'ts-jest',
},
transformIgnorePatterns: [
    '../../../node_modules/(?!@firebase.*/)',
    '../../../node_modules/(?!firebase/)',
    '../../../node_modules/(?!firebase-admin/)',
    '../../../node_modules/(?!firebase-functions/)',
],

当前完整Jest配置:

module.exports = {
  displayName: '[projectName]',
  preset: '../../../jest.preset.js',
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
    },
  },
  transform: {
    '^.+\\.[tj]s$': 'ts-jest',
  },
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  moduleFileExtensions: ['ts', 'js', 'html'],
  coverageDirectory: '../../../coverage/apps/back/[projectName]',
  testEnvironment: 'node',
}

解决方案

1. 优化ts-jest配置与transformIgnorePatterns

修正正则表达式并启用ts-jest的ES模块支持,调整后的Jest配置:

module.exports = {
  displayName: '[projectName]',
  preset: '../../../jest.preset.js',
  globals: {
    'ts-jest': {
      tsconfig: '<rootDir>/tsconfig.spec.json',
      useESM: true, // 启用ES模块支持
    },
  },
  transform: {
    '^.+\\.(ts|js)$': 'ts-jest',
  },
  transformIgnorePatterns: [
    'node_modules/(?!(firebase|firebase-admin|firebase-functions|@firebase)/)'
  ],
  moduleNameMapper: {
    '^(\\.{1,2}/.*)\\.js$': '$1', // 处理ES模块的.js后缀导入
  },
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  moduleFileExtensions: ['ts', 'js', 'html'],
  coverageDirectory: '../../../coverage/apps/back/[projectName]',
  testEnvironment: 'node',
  extensionsToTreatAsEsm: ['.ts'], // 将.ts文件视为ES模块
}

2. 切换到babel-jest处理ES模块

若ts-jest仍存在兼容问题,可改用babel-jest配合TypeScript预设:

  • 安装依赖:npm install --save-dev babel-jest @babel/core @babel/preset-env @babel/preset-typescript
  • 创建.babelrc配置文件:
{
  "presets": [
    ["@babel/preset-env", { "targets": { "node": "current" } }],
    "@babel/preset-typescript"
  ]
}
  • 修改Jest配置:
module.exports = {
  displayName: '[projectName]',
  preset: '../../../jest.preset.js',
  transform: {
    '^.+\\.(ts|js)$': 'babel-jest',
  },
  transformIgnorePatterns: [
    'node_modules/(?!(firebase|firebase-admin|firebase-functions|@firebase)/)'
  ],
  setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
  moduleFileExtensions: ['ts', 'js', 'html'],
  coverageDirectory: '../../../coverage/apps/back/[projectName]',
  testEnvironment: 'node',
}

3. 模拟Firebase依赖

如果上述方案都不生效,可直接在测试中模拟Firebase模块,避免加载真实ES模块代码:
在jest.setup.ts中添加:

jest.mock('firebase-admin', () => ({
  auth: jest.fn().mockReturnValue({
    // 按需模拟auth模块的方法,例如:
    getUser: jest.fn().mockResolvedValue({ uid: 'test-uid' })
  }),
  // 其他需要模拟的Firebase Admin模块
}));

jest.mock('firebase-functions', () => ({
  // 按需模拟firebase-functions的API,例如:
  httpsCallable: jest.fn()
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:05:21