1
0

JestとReact Testing Libraryを使ってテストをする(Next.js)

Posted at

はじめに

Next.jsのライブラリが作成済みの前提で進めます。

作成していない場合、インストールします

$ npx create-next-app@latest
√ What is your project named? ... my-app
√ Would you like to use TypeScript? ... No / Yes =>Yes
√ Would you like to use ESLint? ... No / Yes =>Yes
√ Would you like to use Tailwind CSS? ... No / Yes =>No
√ Would you like to use `src/` directory? ... No / Yes =>Yes
√ Would you like to use App Router? (recommended) ... No / Yes =>Yes
√ Would you like to customize the default import alias (@/*)? ... No / Yes =>No

Jest をインストールする

プロジェクトのルートに移動

$ cd my-app

jest、testing-libraryをインストール

$ npm install --save-dev jest @testing-library/react @testing-library/jest-dom jest-environment-jsdom

jest.config.js ファイルをプロジェクトのルートディレクトリに作成し、以下を追加

jest.config.js
const nextJest = require('next/jest')

const createJestConfig = nextJest({
  // テスト環境の next.config.js と .env ファイルを読み込むために、Next.js アプリケーションへのパスを記載する
  dir: './',
})

// Jest に渡すカスタム設定を追加する
const customJestConfig = {
  // 各テストの実行前に渡すオプションを追加
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  // TypeScript の設定で baseUrl をルートディレクトリに設定している場合、alias を動作させるためには以下のようにする必要があります
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
}

// createJestConfig は、非同期で next/jest が Next.js の設定を読み込めるようにするため、下記のようにエクスポートします
module.exports = createJestConfig(customJestConfig)

jest.setup.jsファイルをプロジェクトのルートディレクトリに作成し、以下を追加

jest.setup.js
import '@testing-library/jest-dom'

test script を package.json に追加する

package.json
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest"           //← 追加
  },

テストコードの作成

  • src/app/__test__ディレクトリを作成
  • __test__/sample.test.jsファイルを作成
sapmle.test.js
import { render, screen } from '@testing-library/react'
import Home from "../page"

describe('Home', () => {
  it('renders a heading', () => {
    render(<Home />)
    const heading = screen.getByText(/Next.js/i);
    expect(heading).toBeInTheDocument()
  })
})

src/app/page.tsxの中身を編集

page.tsx
export default function Home() {
  return (
<>
<h1>Next.js</h1>
</>
  );
}

テストの実行

$ npm run test
 PASS  src/app/__tests__/sample.test.js
  Home
    √ renders a heading (50 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        3.845 s
Ran all test suites.

上記のように表示されれば成功です。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0