ピックアップ
NextjsでのJest導入時の個人的なメモ。
Nextjsでプロジェクト作成するときの、
各種初期導入して、
最新情報を取得して、
Github Copilotのみで進めれるかなとか思ったが、
うまく挙動せず、
諦めて、
公式情報を確認して、
1つずつ、ペコペコやったので、
完全な個人用の断片メモ。
メモ:パッケージマネージャ
npm、yarn、pnpmは、JavaScript/TypeScriptプロジェクトで使われるパッケージマネージャです。
npm
- Node.js公式の標準パッケージマネージャ
- コマンド例:
npm install
- 依存関係を node_modules にフラットにインストール
yarn
- Facebookが開発したnpm互換のパッケージマネージャ
- 高速なインストール、ロックファイルによる一貫性
- コマンド例:
yarn add
- 一部npmより高速・安定
pnpm
- 高速・省スペースなパッケージマネージャ
- 依存パッケージをグローバルに保存し、プロジェクトごとにリンク
- コマンド例:
pnpm install
- ディスク容量を大幅に節約できる
公式サイトの情報
公式サイト
まずは、公式サイトで確認
自分が確認した時点で、
以下のコマンド。
自分が使用してないパッケージマネージャもメモ残す。
npm
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
yarn
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
pnpm
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
が初期導入コマンドとなっていました。
リンクをメモしておきます。
https://nextjs.org/docs/app/guides/testing/jest#manual-setup
Jestの初期設定ファイル生成生成
上記の公式にもある通りに進める。
初期設定ファイルの構築が行えるので、
コマンドからその点を行う。
実行コマンドはこちら
npm init jest@latest
# or
yarn create jest@latest
# or
pnpm create jest@latest
上記実行で、
? Would you like to use Jest when running "test" script in "package.json"? › (Y/n)
と聞かれるので、
追加してもらうので、
「y」で実行する。
? Would you like to use Typescript for the configuration file? › (y/N)
自分の環境では、
TypeScriptの環境なので、
「y」で実行。
? Choose the test environment that will be used for testing › - Use arrow-keys. Return to submit.
❯ node
jsdom (browser-like)
Nextjsで
画面側のテストも実行したいので、
「jsdom (browser-like)」を選択。
? Do you want Jest to add coverage reports? › (y/N)
品質管理やテストの抜け漏れ確認に役立つので、
基本的には「y」を選んで良いのではと。
? Which provider should be used to instrument code for coverage? › - Use arrow-keys. Return to submit.
❯ v8
babel
Next.jsやTypeScriptプロジェクトではv8が推奨のはず、
「v8」を選択。
? Automatically clear mock calls, instances, contexts and results before every test? › (y/N)
「各テストの前に、モック(mock)の呼び出し履歴・インスタンス・コンテキスト・結果を自動的にクリアしますか?」
用語解説
- mock(モック):テスト用のダミー関数やオブジェクト
- calls(呼び出し履歴):モックが呼ばれた記録
- instances(インスタンス):モックで生成されたオブジェクト
- contexts(コンテキスト):関数の実行時の状態
- results(結果):モックの返り値など
これは「y」を選択。
テスト用ファイル準備
こちらも公式サイトをそのまま使用。
配置としては、
自分の環境では、
srcフォルダを使用してるので、
├── src
│ ├── __tests__
│ │ └── page.test.jsx
この配置で、
あとは、公式のコードを使用。
import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
import Page from '../app/page'
describe('Page', () => {
it('renders a heading', () => {
render(<Page />)
const heading = screen.getByRole('heading', { level: 1 })
expect(heading).toBeInTheDocument()
})
})
環境ファイル調整
自分の環境では、
モジュールパスのエイリアスを使っているので、
Optional: Handling Absolute Imports and Module Path Aliases
If your project is using Module Path Aliases,
you will need to configure Jest
to resolve the imports by matching the paths option
in the jsconfig.json file with the moduleNameMapper option
in the jest.config.js file. For example:
こちらに該当するので、
sconfig.json or jsconfig.json
のコードを調整。
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"baseUrl": "./",
"paths": {
"@/components/*": ["components/*"]
}
}
}
これは差分のみ追加でした。
それと、
jest.config.js
こちらは、
moduleNameMapper: {
// ...
'^@/components/(.*)$': '<rootDir>/components/$1',
}
をConfig配下に追加しました。
テスト実行
テスト実行で試します
npm run test
実行すると、
# npm run test
> portfolio-ui-nextjs@0.1.0 test
> jest
PASS src/__tests__/page.test.jsx
Page
✓ renders a heading (67 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 4.706 s
Ran all test suites.
という形でうまく、
テストが完了。
おすすめ書籍
コメント一覧
コメントはまだありません。
コメントを残す