はじめに
Next.jsv15でJestとReact Testing Libraryを設定、テスト実行をしようとしたところ、エラーが発生しました。
問題
公式ドキュメントに沿って、Jestのテスト環境を構築
npm run testを実行するとSupport for the experimental syntax 'jsx' isn't currently enabledエラーが発生しました。
原因
Next.jsのプロジェクトに、通常のJestの設定を行っていたため
通常のJest設定のため、TypeScriptの変換処理ができていませんでした。
公式ドキュメントの以下の文章を見落としていました。
公式ドキュメントより引用
Update your config file to use next/jest. This transformer has all the necessary configuration options for Jest to work with Next.js:
next/jestを使うように設定ファイルを更新してください。このトランスフォーマーには、JestがNext.jsで動作するために必要な設定オプションがすべて含まれています:
解決方法
jest.config.tsの設定を修正
import type { Config } from "jest";
+ import nextJest from "next/jest.js";
+ const createJestConfig = nextJest({
+ // Provide the path to your Next.js app to load next.config.js and .env files in your + test environment
+ dir: "./",
+ });
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
- moduleNameMapper: {}
+ moduleNameMapper: {
+ "^@/(.*)$": "<rootDir>/src/$1",
+ },
- export default config;
+ export default createJestConfig(config);
おわりに
エラーを調べても解決せず、時間がかかってしまいました。
公式ドキュメントに答えあり…しっかり読むことを戒めようと思いました。
参考