Next.js(13.4.1)のプロジェクトにJest+React Testing Libraryを導入してテストを実装する準備

Posted date at 2023-06-18

インプット

Jest+React Testing Library導入

参考:

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)
  • npm scriptを追加*

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 testjest —watchを起動してテストが通ることを確認して動作確認完了。

←ホームに戻る