目次
Laravel Mixで作成したReact環境でテスト実行時にエラーが発生する
Laravel Mixを使用すると、Laravel × React環境を簡単に構築することができます。
今回はそのLaravel Mixで作成したReact環境でJestを用いたテスト実行時をした際にエラーが発生してテストを実行することができなかったため、その際のエラーが解決方法を掲載します。
発生エラー
実行コマンド
yarn test
実行結果
Test suite failed to run
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://jestjs.io/docs/en/configuration.html
エラー解消方法
webpack.config.jsをLaravelのプロジェクト直下へ作成
以下を、Laravelのプロジェクトディレクトリ直下へ作成する。
webpack.config.js
// babel.config.js
module.exports = {
presets: [
'@babel/preset-env',
'@babel/preset-react',
'@babel/preset-flow',
],
plugins: [
'babel-plugin-styled-components',
'@babel/plugin-proposal-class-properties',
]
}
babel-coreをインストール
npm install babel-core@7.0.0-bridge.0 --save-dev
エラーの解決確認
これでちゃんとエラー無くテストが実行できるようになった。
実行コマンド
yarn test
実行結果
yarn run v1.16.0
$ jest
PASS resources/js/tests/components/Sample.test.js
<Sample />
✓ Snapshot (1ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 1.102s
Ran all test suites.
Done in 2.04s.
Jestコマンドが見つからないエラーが発生した場合
発生エラー
実行コマンド
yarn test
実行結果
yarn run v1.16.0
$ jest
/bin/sh: 1: jest: not found
error Command failed with exit code 127.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
エラー解消方法
以下を実行したら解決。
yarn add jest
これでyarn testを実行したら、エラー無くテストが実行できた。
コメント