运行Jest测试时出现意外的令牌“导入”错误?

时间:2018-07-01 21:35:20

标签: vue.js jestjs babel-jest

我知道这个问题已经问过几次了,但是我遇到的所有解决方案似乎都不适合我。尝试为Vue应用程序运行Jest测试时遇到以下错误。

Jest encountered an unexpected token

This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

Here's what you can do:
 • 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://facebook.github.io/jest/docs/en/configuration.html

Details:

/node_modules/vue-awesome/icons/expand.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Icon from '../components/Icon.vue'
                                                                                         ^^^^^^

SyntaxError: Unexpected token import

> 17 | import 'vue-awesome/icons/expand'

.babelrc:

{
  "presets": [
    ["env", {
      "modules": false,
      "targets": {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }]
  ],
  "env": {
    "test": {
      "presets": [
        ["env", { "targets": { "node": "current" }}]
      ]
    }
  }
}
package.json中的

jest配置:

"jest": {
  "moduleFileExtensions": [
    "js",
    "vue"
  ],
  "moduleNameMapper": {
    "^@/(.*)$": "<rootDir>/src/$1"
  },
  "transform": {
    "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
    ".*\\.(vue)$": "<rootDir>/node_modules/vue-jest"
  },
  "snapshotSerializers": [
    "<rootDir>/node_modules/jest-serializer-vue"
  ],
  "moduleDirectories": [
    "node_modules",
    "src"
  ]
}

似乎正在为测试安装的Vue组件的脚本中的初始导入正在运行,但是无法识别模块本身(import Icon from '../components/Icon.vue)中的导入。

我该如何解决?

3 个答案:

答案 0 :(得分:5)

您只需要确保vue-awesome会被玩笑所转换,因此添加 按照您的笑话配置:

transformIgnorePatterns: ["/node_modules/(?!vue-awesome)"],

表示:“忽略{_1}}之外的node_modules中的所有内容。

以下是可能导致此错误的其他问题的详尽列表:https://github.com/facebook/jest/issues/2081

答案 1 :(得分:1)

如果在更新到更新的Jest版本后遇到此问题,请尝试清除Jest的内部缓存:

jest --clearCache

答案 2 :(得分:0)

我们在另一个图书馆遇到了同样的问题。根本原因是我们在代码中有循环依赖。但是错误文本根本没有提到它。就像在这篇文章中一样:“Jest 遇到了一个意想不到的令牌......”