jest Jest encountered an unexpected token import とかexportが読み込めない

vue.jsのテストでjestを利用しています。

jestのバージョンは 27.4.3
nodeは 16.13.0です。

次のようなエラーが出てテストが実行できずに困っていました。

   Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • 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://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /var/www/html/hoge/webpack_src/components/timeTable/templates/TimeTable.vue:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){<template>
                                                                                      ^

    SyntaxError: Unexpected token '<'

       8 | import Vuex from "vuex";
       9 | import {createLocalVue, mount} from "@vue/test-utils";
    > 10 | import TimeTableVue from "../../../../../components/timeTable/templates/TimeTable";
         | ^
      11 | import {FontAwesomeIcon} from '@fortawesome/vue-fontawesome' // 追加
      12 |
      13 |

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (webpack_src/test/unit/specs/class/timeTable/TimeTableVue.spec.js:10:1)

node_modulesの中のimport, export が書いてあるところで止まっちゃうんですよ。

これについて平たく説明すると、jest は nodeで動作するのですが、nodeはexport や import という文法を知らないので、SyntaxErrorになってしまうというわけです。

下記のサイトに、解決方法が載っていました。有難うございます!

ts-jestが外部ライブラリをimportできない場合の対処方

https://media-massage.net/blog/ts-jest%E3%81%8C%E5%A4%96%E9%83%A8%E3%83%A9%E3%82%A4%E3%83%96%E3%83%A9%E3%83%AA%E3%82%92import%E3%81%A7%E3%81%8D%E3%81%AA%E3%81%84%E5%A0%B4%E5%90%88%E3%81%AE%E5%AF%BE%E5%87%A6%E6%96%B9/

このとき設定ファイルを.babelrcとして作成してしまうと意図通りに動作しないのでbabel.config.jsとすること。.babelrcで設定ファイルを作るとデフォルトではnode_modules内のファイルには設定が適用されない。

そうだったのか!目からうろこでした(泣)

というわけで、今まで.babelrc で書いていたところを babel.config.js にしたら直りました。

リンク先とほぼ同じですが、babel.config.js を載せておきます。

module.exports = {
    "presets": [
        [
            "@babel/preset-env",
            {
                "modules": false,
                "useBuiltIns": "usage",
                "targets": "> 0.25%, not dead",
                "corejs": 3
            }
        ]
    ],
    "env": {
        "test": {
            "presets": [["@babel/preset-env", {"targets": {"node": "current"}}]]
        }
    }
}

jest.conf.jsは次の通り。

const path = require('path')

module.exports = {
  rootDir: path.resolve(__dirname, '../../../'),
  moduleFileExtensions: [
    'js',
    'json',
    'vue'
  ],
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/webpack_src/$1',
    '\\.(css|less)$': 'identity-obj-proxy'
  },
  transform: {
    '.*\\.(vue)$': 'vue-jest',
    '^.+\\.js$': 'babel-jest'
  },
  transformIgnorePatterns: [
  ],
  testPathIgnorePatterns: [
    '<rootDir>/webpack_src/test/e2e'
  ],
  snapshotSerializers: ['<rootDir>/node_modules/jest-serializer-vue'],
  setupFiles: ['<rootDir>/webpack_src/test/unit/setup'],
  coverageDirectory: '<rootDir>/webpack_src/test/unit/coverage',
  collectCoverageFrom: [
    'webpack_src/**/*.{js,vue}',
    '!webpack_src/main.js',
    '!**/node_modules/**'
  ],
  testURL: 'http://localhost/',
  globalSetup: '<rootDir>/webpack_src/test/unit/global-setup.js'
}

次の

transformIgnorePatterns: [
]

は空なので、指定しなくてもいいかと思いそうですが、これを削除すると、前述のエラーが出ます。

Jestの公式サイトによると、

https://jestjs.io/ja/docs/configuration#transformignorepatterns-arraystring

transformIgnorePatterns  のデフォルト値が

 
{ "transformIgnorePatterns": ["/node_modules/", "\\.pnp\\.[^\\\/]+$"] }

なので、書かないとnode_modules の中をtransform してくれないからじゃないかなって考えています。(←ただの推測でちゃんと確認してません。)