JestをNext.jsで設定する
JestとReact Testing Libraryは、Unit TestingとSnapshot Testingによく使用されます。このガイドでは、JestをNext.jsで設定し、最初のテストを書く方法を紹介します。
Good to know:
async
server componentはReactエコシステムにおいて新しいため、Jestは現在それをサポートしていません。同期的なserver componentとclient componentのためのunit testsを実行することは可能ですが、async
componentにはE2E testsを使用することをお勧めします。
クイックスタート
create-next-app
を使用して、Next.jsのwith-jest例を使ってすぐに始めることができます:
npx create-next-app@latest --example with-jest with-jest-app
手動設定
Next.js 12のリリース以降、Next.jsにはJestのための組み込みの設定が用意されています。
Jestを設定するには、jest
と以下のパッケージを開発依存としてインストールします:
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
# または \{#or}
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
# または \{#or}
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
以下のコマンドを実行して、基本的なJest設定ファイルを生成します:
npm init jest@latest
# または \{#or}
yarn create jest@latest
# または \{#or}
pnpm create jest@latest
これにより、プロジェクトのためにJestを設定する一連のプロンプトが表示され、jest.config.ts|js
ファイルが自動的に作成されます。
設定ファイルを更新してnext/jest
を使用します。このトランスフォーマーには、JestがNext.jsで動作するために必要なすべての設定オプションが含まれています:
- TypeScript
- JavaScript
import type { Config } from 'jest'
import nextJest from 'next/jest.js'
const createJestConfig = nextJest({
// テスト環境でnext.config.jsと.envファイルを読み込むためにNext.jsアプリへのパスを指定します
dir: './',
})
// Jestに渡すカスタム設定を追加します
const config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// 各テストが実行される前に追加の設定オプションを追加します
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
// createJestConfigは、next/jestが非同期のNext.js設定を読み込めるようにこの方法でエクスポートされます
export default createJestConfig(config)
const nextJest = require('next/jest')
/** @type {import('jest').Config} */
const createJestConfig = nextJest({
// テスト環境でnext.config.jsと.envファイルを読み込むためにNext.jsアプリへのパスを指定します
dir: './',
})
// Jestに渡すカスタム設定を追加します
const config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// 各テストが実行される前に追加の設定オプションを追加します
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
// createJestConfigは、next/jestが非同期のNext.js設定を読み込めるようにこの方法でエクスポートされます
module.exports = createJestConfig(config)
内部的には、next/jest
が自動的にJestを設定しており、以下を含みます:
- Next.js Compilerを使用した
transform
の設定 - スタイルシート(
.css
、.module.css
、およびそのscssバリアント)、画像インポート、およびnext/font
の自動モック .env
(およびそのすべてのバリアント)をprocess.env
にロード- テストの解決と変換から
node_modules
を無視 - テストの解決から
.next
を無視 - SWC変換を有効にするフラグのために
next.config.js
をロード
Good to know: 環境変数を直接テストするには、別のセットアップスクリプトまたは
jest.config.ts
ファイルで手動でロードしてください。詳細については、Test Environment Variablesを参照してください。
オプション: 絶対インポートとモジュールパスエイリアスの処理
プロジェクトでモジュールパスエイリアスを使用している場合、jsconfig.json
ファイルのパスオプションとjest.config.js
ファイルのmoduleNameMapper
オプションを一致させることで、Jestがインポートを解決できるように設定する必要があります。例えば:
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"baseUrl": "./",
"paths": {
"@/components/*": ["components/*"]
}
}
}
moduleNameMapper: {
// ...
'^@/components/(.*)$': '<rootDir>/components/$1',
}
オプション: Jestをカスタムマッチャーで拡張する
@testing-library/jest-dom
には、.toBeInTheDocument()
のような便利なカスタムマッチャーが含まれており、テストを書くのが容易になります。Jest設定ファイルに次のオプションを追加することで、すべてのテストでカスタムマッチャーをインポートできます:
- TypeScript
- JavaScript
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
次に、jest.setup
内で次のインポートを追加します:
- TypeScript
- JavaScript
import '@testing-library/jest-dom'
import '@testing-library/jest-dom'
Good to know:
extend-expect
はv6.0
で削除されましたので、バージョン6より前の@testing-library/jest-dom
を使用している場合は、代わりに@testing-library/jest-dom/extend-expect
をインポートする必要があります。
各テストの前に追加の設定オプションを追加する必要がある場合は、上記のjest.setup
ファイルに追加できます。
package.json
にテストスクリプトを追加する
最後に、Jestのtest
スクリプトをpackage.json
ファイルに追加します:
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest",
"test:watch": "jest --watch"
}
}
jest --watch
は、ファイルが変更されるとテストを再実行します。その他のJest CLIオプションについては、Jestドキュメントを参照してください。
最初のテストを作成する
プロジェクトはテストを実行する準備が整いました。プロジェクトのルートディレクトリに__tests__
というフォルダを作成します。
例えば、<Page />
コンポーネントが見出しを正常にレンダリングするかどうかを確認するテストを追加できます:
import Link from 'next/link'
export default function Page() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}
import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
import Page from '../app/page'
describe('Page', () => {
it('renders a heading', () => {
render(<Page />)
const heading = screen.getByRole('heading', { level: 1 })
expect(heading).toBeInTheDocument()
})
})
オプションとして、コンポーネントに予期しない変更がないかを追跡するためにスナップショットテストを追加できます:
import { render } from '@testing-library/react'
import Page from '../app/page'
it('renders homepage unchanged', () => {
const { container } = render(<Page />)
expect(container).toMatchSnapshot()
})
テストを実行する
次に、以下のコマンドを実行してテストを実行します:
npm run test
# または \{#or}
yarn test
# または \{#or}
pnpm test
追加リソース
さらに読みたい場合は、次のリソースが役立つかもしれません:
- Next.js with Jest example
- Jest Docs
- React Testing Library Docs
- Testing Playground - 良いテストプラクティスを使用して要素をマッチさせます。