Next.js(13.4.1)のプロジェクトにJest+React Testing Libraryを導入してテストを実装する準備
Jest+React Testing Library導入
インストールコマンド
以下のパッケージをインストールします:
npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
設定ファイル作成
プロジェクトルートにjest.config.mjsを作成し、以下の設定を追加します:
import nextJest from 'next/jest.js'
const createJestConfig = nextJest({
dir: './',
})
const config = {
testEnvironment: 'jest-environment-jsdom',
}
export default createJestConfig(config)
npm scriptの追加
package.jsonのscriptセクションに以下を追加:
"test": "jest --watch"
動作確認
プロジェクトルートに__tests__ディレクトリを作成し、page.test.tsxファイルを追加:
import { render, screen } from '@testing-library/react'
import '@testing-library/jest-dom'
import Home from '../src/app/page'
describe('Home', () => {
it('Topページのタイトル確認', () => {
render(<Home />)
const heading = screen.getByRole('heading', {
name: "H1タイトル",
})
expect(heading).toBeInTheDocument()
})
})
npm run testを実行してテストが成功することを確認します。