开玩笑:不能在模块外使用导入语句

und*_*ned 16 import module jestjs

使用 Jest 运行测试时出现错误,我尝试修复此错误 2 小时。但是,我无法修复它。我的模块正在使用gapi-script包,并且此包中发生错误。但是,我不知道为什么会发生这种情况以及如何解决它。

开玩笑的配置文件

module.exports = {
  "collectCoverage": true,
  "rootDir": "./",
  "testRegex": "__tests__/.+\\.test\\.js",
  "transform": {
    '^.+\\.js?$': "babel-jest"
  },
  "moduleFileExtensions": ["js"],
  "moduleDirectories": [
    "node_modules",
    "lib"
  ]
}
Run Code Online (Sandbox Code Playgroud)

babel.config.js

module.exports = {
  presets: [
    '@babel/preset-env',
  ]
};
Run Code Online (Sandbox Code Playgroud)

方法.test.js

import methods, { typeToActions } from '../lib/methods';
Run Code Online (Sandbox Code Playgroud)

方法.js

import { gapi } from "gapi-script";
...
Run Code Online (Sandbox Code Playgroud)

错误信息

C:\haram\github\react-youtube-data-api\node_modules\gapi-script\index.js:1 ({"Object.":function(module,exports,require,__dirname,__filename,global,jest){导入 { gapi, gapiComplete } from './gapiScript';

SyntaxError: Cannot use import statement outside a module
Run Code Online (Sandbox Code Playgroud)

我的设置有什么问题?

Set*_*eth 9

在撰写本文时,Jest 正在为 ES6 模块提供支持。您可以在此处跟踪进度:

https://jestjs.io/docs/en/ecmascript-modules

现在,您可以通过运行以下命令来消除此错误:

node --experimental-vm-modules node_modules/.bin/jest
Run Code Online (Sandbox Code Playgroud)

而不是简单地:

jest
Run Code Online (Sandbox Code Playgroud)

在使用此解决方案之前,请务必检查链接。


小智 8

我在 Paulo Coghi 对另一个问题的回答的帮助下解决了这个问题 -

Jest 支持 ES6 导入/导出吗?

步骤1:

将测试环境添加到项目根目录中的 .babelrc 中:

{
  "env": {
    "test": {
      "plugins": ["@babel/plugin-transform-modules-commonjs"]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

第2步:

安装 ECMAScript 6 转换插件:

npm install --save-dev @babel/plugin-transform-modules-commonjs
Run Code Online (Sandbox Code Playgroud)


Onn*_*Zee 5

Jest 需要 babel 来处理模块。对于单独的测试,您不需要jest.config.js,只需将测试文件命名为 xxx.spec.js 或 xxx.test.js 或将文件放在名为test的文件夹中。

我使用这个babel.config.js

module.exports = function (api) {
  api.cache(true)

  const presets = [
    "@babel/preset-env"
  ]

  return {
    presets
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您的设置不太复杂,则无需在 package.json 中添加 "type": "module" 或使用其他答案中所述的 mjs。