我知道这个问题已经被问过很多次,但是我遇到的所有解决方案似乎都无法解决我的问题。 我在试图运行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
)没有被识别。
复现此问题的样板库:github.com/DonaldPeat/stackoverflow-jest-question
我该如何解决这个问题?
vue-cli
创建项目的吗?如果是,使用的是哪个版本?如果不是,能给一个在 GitHub 上表现出这个问题的 repo 的链接吗?顺带一提,我用vue-cli
创建的项目 (3.0.0-rc.3
) 无法重现这个问题。 - tony19vue-cli
。我创建了一个样板库来重新创建这个问题 https://github.com/DonaldPeat/stackoverflow-jest-question - Don