【问题标题】:Jest: Cannot use import statement outside a module笑话:不能在模块外使用 import 语句
【发布时间】:2020-04-29 18:31:37
【问题描述】:

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

jest.config.js

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

babel.config.js

module.exports = {
  presets: [
    '@babel/preset-env',
  ]
};

methods.test.js

import methods, { typeToActions } from '../lib/methods';

methods.js

import { gapi } from "gapi-script";
...

错误信息

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

SyntaxError: Cannot use import statement outside a module

我的设置有什么问题?

【问题讨论】:

标签: import module jestjs


【解决方案1】:

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

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

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

node --experimental-vm-modules node_modules/.bin/jest

而不是简单地:

jest

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

【讨论】:

  • 这是巨大的!我花了太长时间寻找这个解决方案。所有的测试都在工作,然后我写了几个小时的代码,一切都失败了。找到很多关于如何更新配置以使事情通过的文档 - 尝试并失败了一段时间,然后找到了这个。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    Does Jest support ES6 import/export?

    第 1 步:

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

    {
      "env": {
        "test": {
          "plugins": ["@babel/plugin-transform-modules-commonjs"]
        }
      }
    }
    

    第 2 步:

    安装 ECMAScript 6 转换插件:

    npm install --save-dev @babel/plugin-transform-modules-commonjs
    

    【讨论】:

    • 这适用于 VenillaJs,谢谢
    猜你喜欢
    • 2020-05-09
    • 1970-01-01
    • 2020-02-09
    • 2021-03-22
    • 2020-01-27
    • 2020-02-11
    • 2020-12-11
    相关资源
    最近更新 更多