Skip to content

Next.jsのテスト

Next.jsアプリケーションのテストは、アプリケーションの品質を保証するために重要です。JestやReact Testing Libraryを使用して、コンポーネントやページのテストを行うことが一般的です。

Jestは、JavaScriptのテストフレームワークで、Next.jsプロジェクトで広く使用されています。

Terminal window
npm install --save-dev jest
npm install --save-dev @testing-library/react
npm install --save-dev @testing-library/jest-dom

jest.config.jsファイルを作成し、以下のように設定します。

jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/$1',
},
};

React Testing Libraryは、Reactコンポーネントのテストを行うためのライブラリです。

import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import Home from '@/pages/index';
test('renders a heading', () => {
render(<Home />);
const heading = screen.getByRole('heading', {
name: /welcome to next.js!/i,
});
expect(heading).toBeInTheDocument();
});

テストを実行するには、以下のコマンドを使用します。

Terminal window
npm test

JestとReact Testing Libraryを使用することで、Next.jsアプリケーションのコンポーネントやページの動作を確実にテストし、品質を保証することができます。