この質問は何度も聞かれていることは承知していますが、私が見つけた解決策はどれもうまくいかないようです。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
これを解決するにはどうすればよいですか?
ベストアンサー1
vue-awesome
jest によって変換されることを確認する必要があるだけなので、jest 構成に次の内容を追加します。
transformIgnorePatterns: ["/node_modules/(?!vue-awesome)"],
これは、「 を除く node_modules 内のすべてを無視しますvue-awesome
。 」 を意味します。
また、このエラーの原因となる可能性のあるその他の問題の完全なリストは次のとおりです。https://github.com/facebook/jest/issues/2081