インプット
参考:
Optimizing: Testing | Next.js (nextjs.org)
npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
rootにjest.config.mjs
を作成し以下をペースト
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: './', }) // Add any custom config to be passed to Jest /** @type {import('jest').Config} */ const config = { // Add more setup options before each test is run // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], testEnvironment: 'jest-environment-jsdom', } // createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async export default createJestConfig(config)
package.jsonのscriptに"test": "jest --watch"
を追加
__tests__
ディレクトリをプロジェクトルートに作成。
/__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 />) // h1タグで「H1タイトル」と記載されている前提なら。 const heading = screen.getByRole('heading', { name: "H1タイトル", }) expect(heading).toBeInTheDocument() }) })
npm run test
でjest —watch
を起動してテストが通ることを確認して動作確認完了。