如何在使用jest和babel-loader时,使用d3.js v7?

6

我有一些使用d3.js v6.7.0的React项目,我能够在Windows 10上使用jest 27.2.0进行测试。

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',
      },

如果我将d3.js升级到使用ES6模块的版本7.0.1,当运行我的测试时,我会遇到以下错误:

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.
      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:

    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";

=> 我应该如何调整我的配置以使测试再次运行?

a) 我尝试使用适应的webpack测试脚本和cross-env启用实验性节点功能:

cross-env NODE_OPTIONS=--experimental-vm-modules jest
b) 我尝试适应 jest transformIgnorePatterns
transformIgnorePatterns: [
     "/node_modules/(?!(d3.*))"
  ],

c) 我尝试将 node_modules/d3 包含到 webpack babel-loader 中。

然而,我还没有找到可行的配置方式。

相关链接:

https://github.com/nrwl/nx/issues/812

https://github.com/webpack/webpack/issues/2031

如何编写 Jest 的 transformIgnorePatterns

webpack 构建中出现意外的 "export" 标记

1个回答

0

我曾经遇到过完全相同的问题,最终通过为 d3 配置一个 moduleNameMapper 来解决(或更准确地说是工作方式)。由于我没有任何合理的映射内容,所以我只是创建了一个名为 test/d3.js 的文件,里面只包含一个解释其用途的注释。

jest.config.js 中,配置最终看起来像这样:

  moduleNameMapper: {
    "^d3$": "<rootDir>/test/d3.js"
  },

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接