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

如何配置Jest与babel-loader适配d3.js v7 解决测试运行报错

D3 v7升级后Jest测试报错修复方案

问题背景

现有React项目使用d3.js v6.7.0版本,Windows 10系统下通过jest 27.2.0运行测试正常。升级d3到使用ES6模块的v7.0.1版本后,测试运行抛出语法错误,提示无法识别export关键字。

原有配置

jest.config.js 部分配置

testEnvironment: "jsdom",
testRunner: "jest-jasmine2",
transform: {
    '^.+\\.jsx?$': 'babel-jest',
},
transformIgnorePatterns: [
     "\\\\node_modules\\\\"
],

webpack.config.js 部分配置

module: {
    rules: [
      {
        test: /\.(jsx|js)$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
    ]
}

报错详情

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.

    Details:

    C:\python_env\workspace\visualization\frontEnd\node_modules\d3\src\index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){export * from "d3-array";

已尝试未生效方案

  • 配合cross-env开启Node实验性特性,修改测试启动脚本为:
cross-env NODE_OPTIONS=--experimental-vm-modules jest
  • 调整Jest的transformIgnorePatterns配置:
transformIgnorePatterns: [
     "/node_modules/(?!(d3.*))"
  ],
  • 将node_modules/d3纳入webpack babel-loader的编译范围

正确调整步骤

  1. 修正jest.config.js的transformIgnorePatterns配置,兼容Windows和类Unix系统的路径分隔符,将所有d3相关包排除在转译忽略列表外:
transformIgnorePatterns: [
  `[/\\\\]node_modules[/\\\\](?!(d3|d3-.*)[/\\\\])`
]

该配置中的[/\\\\]可同时匹配正斜杠(类Unix系统路径)和反斜杠(Windows系统路径),确保所有d3相关的ES模块都会被babel-jest转译。
2. 检查Babel配置(.babelrc、babel.config.json等),确保@babel/preset-env配置正确,测试环境下会将ES6模块转译为CommonJS格式:

{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "node": "current"
      },
      "modules": "auto"
    }],
    "@babel/preset-react"
  ]
}

如果之前为了webpack tree-shaking设置了modules: false,需要新增环境覆盖配置,在test环境下将modules设为commonjs。
3. 回退测试启动脚本,移除NODE_OPTIONS=--experimental-vm-modules参数,该参数仅适用于纯ES模块的Jest项目,与当前CommonJS配置冲突。
4. 无需修改webpack配置,Jest运行测试不依赖webpack编译规则,调整webpack配置对测试场景无作用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:54:00