フレームワークをNext.jsへ移行することを考えている
このとき、Jestで書いたテストもNext.jsに移行することを考えているが、ドキュメントを読むとNext.js 12 のリリース以降、Next.jsにはnext/jest
という組み込みモジュールが用意されていることを知った
また、テストの実行にRustコンパイラを用いるか、従来のBabelを用いるかの選択もできるみたい
せっかくなので、Rustコンパイラを使うようにしてみる
ドキュメントにあるように、以下のような jest.config.js を用意する
const nextJest = require('next/jest') const createJestConfig = nextJest({ // Provide the path to your Next.js app to load next.config.js and .env files in your test environment dir: './', }) // Add any custom config to be passed to Jest /** @type {import('jest').Config} */ const customJestConfig = { // Add more setup options before each test is run // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work moduleDirectories: ['node_modules', '<rootDir>/'], testEnvironment: 'jest-environment-jsdom', } // createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async module.exports = createJestConfig(customJestConfig)
これに加えて、今使っているJestの設定ではモジュールのパスにエイリアスを設定して絶対パスでimportしているため、これを設定したい
jestに渡す設定は上記のcustomJestConfig
内に記載する
なので、以下のように記載するとモジュールのパスにエイリアスを設定することができる
const customJestConfig = { // Add more setup options before each test is run // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work moduleDirectories: ["node_modules", "<rootDir>/"], testEnvironment: "jest-environment-jsdom", moduleNameMapper: { "^@/(.*)$": "<rootDir>/src/$1", }, };
これで簡単にテストの移行ができた