ホーム

Jestとは?Next.js(React)への導入方法について解説

作成日: 2023-4-25

更新日: 2023-9-28

Jestとは?Next.js(React)への導入方法について解説

この記事を読んだ後に理解できること


  • jestの概要
  • Next.jsへの導入方法


Jestとは?


Jestはjavascriptのテスティングフレームワークです。

javascriptにおけるテストの基本機能を提供するフレームワークといったところです。

Jestだけでもjavascriptフレームワークのテストを書くことはできるかもしれませんが、かなり時間がかかってしまいます。


そのため、それぞれのフレームワークに対応したTesting Libraryを使うことが一般的です。

Reactが推奨しているTesting LibraryはReact Testing Libraryになります。

Next.jsでの導入方法


アプリケーション作成時



一番簡単なのは、アプリケーション作成コマンドにオプションを付け加えることです。

以下のコマンドで、JestとReact Testing Libraryを含んだNext.jsアプリケーションの導入が可能です。

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


以下のようなディレクトリ構造になります。

.
├── README.md
├── __tests__
│   ├── __snapshots__
│   │   └── snapshot.tsx.snap
│   ├── index.test.tsx
│   └── snapshot.tsx
├── jest.config.js
├── jest.setup.js
├── next-env.d.ts
├── package-lock.json
├── package.json
├── pages
│   ├── _app.tsx
│   ├── index.module.css
│   └── index.tsx
├── public
│   ├── favicon.ico
│   └── vercel.svg
├── styles
│   └── global.css
├── tsconfig.json
└── types.d.ts


  • jest.setup.js


// Optional: configure or set up a testing framework before each test.
// If you delete this file, remove `setupFilesAfterEnv` from `jest.config.js`


// Used for __tests__/testing-library.js
// Learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom/extend-expect'


  • 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
const customJestConfig = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
  moduleNameMapper: {
    // Handle module aliases (this will be automatically configured for you soon)
    '^@/components/(.*)$': '<rootDir>/components/$1',


    '^@/pages/(.*)$': '<rootDir>/pages/$1',
  },
  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)


  • __tests__/index.test.tsx


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


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


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


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


  • snapshotは省略
    • 文字通り、期待した通り表示されているかを確認するテスト


既存プロジェクトに追加


以下コマンドを入力

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


プロジェクトのルートディレクトリに以下ファイルを追加

  • 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)



next/jest を利用すると設定により以下を自動でやってくれます。

  • SWCを使ったセットアップ
  • スタイルシート、画像の自動モック化
  • envの読み込み
    • env.test等
  • node_modules、./nextを参照しない
  • SWC利用のフラグ設定


最後にpackage.jsonのscriptsにテストコマンドを追加します。

// pacakge.json

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


最低限のセットアップは以上で終了です。

さいごに


フロントエンドのテストは軽視されがちな傾向があります。

TypeScriptではなくJavaScriptで書かれているフロントエンドアプリケーションは、予期せぬバグが発生する可能性が高いので、テストを書いておくと比較的安全なアプリケーションが構築できます。