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

ts-jest环境下Mongoose/MongoDB与ESM不兼容配置问题

Jest 适配 Mongoose/MongoDB 驱动的 TypeScript 项目配置方案

问题场景

为使用 Mongoose(自动引入 MongoDB 驱动)的 Node Express/TypeScript 应用配置 Jest 测试环境时,常规配置无法实现 Jest 与 MongoDB 驱动的兼容运行,固定触发两类报错。

两类典型报错

1. ESM 语法未转译报错

未对 MongoDB 驱动做转译排除时,触发以下语法错误:

chart-review-server2.0/node_modules/mongodb/src/bson.ts:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import type {
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

2. 栈溢出报错

仅在transformIgnorePatterns中添加mongodb排除规则后,触发递归调用栈溢出:

RangeError: Maximum call stack size exceeded

      at Object.get [as ObjectId] (node_modules/mongodb/src/bson.ts:38:3)
      at Object.get [as ObjectId] (node_modules/mongodb/src/bson.ts:38:3)...

原有配置参考

原 jest.config.js

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  transformIgnorePatterns: [`node_modules/(?!(mongodb))`],
  transform: {
    '^.+\.ts?$': 'ts-jest'
  },
  moduleDirectories: [ "node_modules", "src", "test"],
  verbose: true,
  testMatch: ["<rootDir>/test/*(*.)+(test).+(ts)"],
  setupFiles: [
    'dotenv/config'
  ],
};

原 tsconfig.json

{
  "compilerOptions": {
    "lib": [
      "es6"
    ],
    "module": "commonjs",
    "target": "es5",
    "rootDirs": [
      "./src"
    ],
    "outDir": "./dist",
    "baseUrl": "./src",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "allowJs": true,
    "downlevelIteration": true,
    "isolatedModules": false,
    "noEmit": true

  },
  "include": [
    "src/**/*.ts",
    "test/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "types": [
    "node"
  ],
  "typeRoots": [
    "node_modules/@types"
  ]
}

问题根因

  • 新版 MongoDB 驱动依赖bson包,原有transformIgnorePatterns规则仅覆盖mongodb本身,未将bson纳入转译范围,部分场景下仍会加载未转译的ESM源码
  • 原有transform规则仅匹配.ts后缀文件,MongoDB 驱动产物中包含.js格式的ESM代码,无法被ts-jest处理
  • ts-jest默认编译配置未适配MongoDB驱动中bson模块的循环引用逻辑,导致ObjectId的getter递归调用触发栈溢出
  • tsconfig中rootDirs仅配置了./src,未包含测试文件所在的./test目录,会导致ts-jest编译时路径解析异常

修复方案

1. 更新 jest.config.js 配置

module.exports = {
  preset: "ts-jest",
  testEnvironment: "node",
  // 同时将mongodb、bson纳入转译范围,不被默认忽略
  transformIgnorePatterns: [`node_modules/(?!(mongodb|bson))/`],
  transform: {
    // 同时匹配ts、js后缀文件,覆盖依赖中的JS格式ESM代码
    '^.+\.(ts|js)$': 'ts-jest'
  },
  moduleDirectories: [ "node_modules", "src", "test"],
  verbose: true,
  // 修正testMatch规则,支持test目录下多层级的测试文件
  testMatch: ["<rootDir>/test/**/*(*.)+(test).+(ts)"],
  setupFiles: [
    'dotenv/config'
  ],
  // 新增ts-jest专属编译配置,适配MongoDB驱动的转译需求
  globals: {
    'ts-jest': {
      tsconfig: {
        target: 'es2019',
        module: 'commonjs',
        allowJs: true,
        esModuleInterop: true,
        skipLibCheck: true
      }
    }
  }
};

2. 调整 tsconfig.json 配置

将compilerOptions.rootDirs字段修改为同时包含src和test目录:

"rootDirs": [
  "./src",
  "./test"
],

其余配置保持原有逻辑即可。

3. 清理缓存后执行测试

配置修改完成后,先执行命令清理Jest的历史转译缓存,避免旧缓存干扰:

npx jest --clearCache

之后重新执行测试命令即可正常运行,两类报错均会消失。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 07:21:21