0
1

More than 1 year has passed since last update.

Next.jsのテスト入門

React.js初心者でもテストの重要さはよく知っています。
テストを書くことは、技術的負債を少しでも減らすことへの第一歩です。

Next.jsでのテストのベストプラクティスを調べてみました。

単体テストについては、Jest & React Testing Frameworkがベストプラクティスになると思います。

E2Eテストについては、Cypress、Playwright、Seleniumなどを組み合わせるみたいです。

Jestと React Testing Libraryを使うには、

1.Jtestのインストール

npx create-next-app@latest --example with-jest with-jest-app

2.Jestのセットアップ(Rustコンパイラを使用)

jest-environment-jsdom@testing-library/react@testing-library/jest-domをインストールします。

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

3.プロジェクトのルートにjest.config.jsファイルを作成して以下を追記します。

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

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 customJestConfig = {
  // Add more setup options before each test is run
  // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
  moduleDirectories: ['node_modules', '<rootDir>/'],
  testEnvironment: 'jest-environment-jsdom',
}

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig)

4.テストの作成

テストスクリプトをpackage.jsonに追加する。

"scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start",
  "test": "jest --watch"
}

jest --watchファイルが変更されたときにテストを再実行します。

最初のテストを作成する

プロジェクトでテストを実行する準備が整いました。__tests__プロジェクトのルート ディレクトリのフォルダーにテストを追加することで、Jest の規則に従います。

たとえば、コンポーネントが見出しを正常にレンダリングするかどうかを確認するテストを追加できます。

// __tests__/index.test.jsx

import { render, screen } from '@testing-library/react'
import Home from '../pages/index'
import '@testing-library/jest-dom'

describe('Home', () => {
  it('renders a heading', () => {
    render(<Home />)

    const heading = screen.getByRole('heading', {
      name: /welcome to next\.js!/i,
    })

    expect(heading).toBeInTheDocument()
  })
})

テストの実行

以下を実行するとテストが開始されます。

npm run test

実行すると成功または失敗が表示されます。

以上になります。
ありがとうございます。

0
1
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
0
1