環境
- macOS Monterey 12.0.1
- VSCode
- node.js v18.6.0
- npm 8.13.2
- Typescript4.6.4
Jestの導入
ライブラリインストール
- Typescriptを使用する前提としていますが、Javascriptでも問題ないです(
@types/jest ts-jest
は不要) - 参考:https://typescript-jp.gitbook.io/deep-dive/intro-1/jest
$ npm i jest @types/jest ts-jest -D
設定ファイルの追加
- プロジェクトのルートに、jest.config.jsを作成
- テスト対象のコードがあるディレクトリやファイルの拡張子などを設定
- 以下の条件の場合、jest.config.js内にCommonJs形式で記述するとエラーになるので注意
- package.jsonで”type”: “module”を指定している
- TypeScriptを使用している
export default {
"roots": [
"<rootDir>/src"
],
"testMatch": [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
},
}
# NG
module.exports = {
・・・
}
テストコマンド実行
- package.jsonにテスト実行用のnpm scriptsを追加
- watchオプションをつけると、テストコードに変更が加わると、自動でテストが走る
- verboseオプションをつけると、コンソールへのテストの実行結果が見やすくなる
{
"test": "jest"
}
実行する
$ npm run test
PASS src/classes/Recipe/Recipe.test.ts
✓ レシピオブジェクトを生成できる (3 ms)
PASS src/classes/Recipe/RecipeList.test.ts
✓ レシピリストが空かどうかチェックできる (2 ms)
✓ レシピリストにレシピを追加できる
✓ レシピリストのレシピ数をカウントできる
Test Suites: 2 passed, 2 total
Tests: 4 passed, 4 total
Snapshots: 0 total
Time: 4.033 s
Ran all test suites related to changed files.
CIへの組み込み
- 基本的には、new work flowからnode.jsの雛形のものを使用するだけでOK
- ただ、上記はテストのみでデプロイのフローがないため、node_modulesのキャッシュなどと共に別途追加した

Build software better, together
GitHub is where people build software. More than 100 million people use GitHub to discover, fork, and contribute to over 330 million projects.