Babel.js Jest无法识别ECMAScript模块

mcvgt66p  于 5个月前  发布在  Babel
关注(0)|答案(1)|浏览(74)

运行测试时出现错误
Jest无法解析文件。当您的代码或其依赖项使用非标准JavaScript语法时会发生这种情况。

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import { useState, useEffect } from 'react';
    > 2 | import axios from 'axios';
        | ^
      3 |
      4 | const useTreeDataFetching = (url) => {
      5 |   const [data, setData] = useState([]);

      at Runtime.createScriptFromCode (node_modules/react-scripts/node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/hooks/useTreeDataFetching.js:2:1)
      at Object.<anonymous> (src/components/TreeList/TreeList.js:3:1)
      at Object.<anonymous> (src/tests/TreeList.test.js:3:1)

字符串
我的package.json文件

"devDependencies": {
    "@babel/core": "^7.23.5",
    "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
    "@babel/preset-env": "^7.23.5",
    "@babel/register": "^7.22.15",
    "@testing-library/jest-dom": "^6.1.4",
    "@testing-library/react": "^14.1.0",
    "babel-jest": "^29.7.0",
    "jest": "^29.7.0",
    "prettier": "3.0.3"
  },
  "jest": {
    "transform": {
      "^.+\\.js$": "babel-jest"
    }
  }

r8xiu3jd

r8xiu3jd1#

默认情况下,Jest不理解像import这样的ESM指令,而是期望CJS(require())。它确实有一个实验模式来支持导入,但还没有准备好生产-如果你想尝试这个,请参阅https://jestjs.io/docs/ecmascript-modules
典型的方法是使用babel-jest转换文件,使其使用require()而不是import。如果这样做,必须正确配置babel以输出CJS而不是ESM。有各种方法可以做到这一点,但最简单的方法是使用

presets: [['@babel/preset-env', { targets: { node: 'current' } }]],

字符串
不过,请确保此配置仅在运行测试时适用,因为此代码可能无法在浏览器中正常工作。
你还会发现,jest默认情况下不会转换node_modules中的代码,假设库模块将提供CJS -这并不总是正确的,但你可以通过调整transformIgnorePatterns来解释这一点-有关详细信息,请参阅https://jestjs.io/docs/configuration#transformignorepatterns-arraystring。

相关问题