毎回新規プロジェクトを立ち上げるたびにどれを導入すればよいのか忘れてしまうのでメモとして残しておきます。
Jest を導入する
以下で Jest を導入する。
yarn add -D jestpackage.json に以下を追記し yarn test でテストが実行可能にする。
{
"scripts": {
"test": "jest"
}
}参考: https://jestjs.io/ja/docs/getting-started
TypeScript でテストを書けるようにする
Jest はテスト実行時に型チェックを行わないらしい。型チェックを行いたい場合は別途 ts-jest を導入する必要がある。
yarn add -D ts-jest @types/jest ts-node設定ファイルを生成する。
yarn jest --init でも設定ファイルを生成できるが対話形式で多少煩雑なため ts-jest から生成しています。
yarn ts-jest config:inittsconfig.test.json に jest 用の tsconfig を定義していきます。
{
"extends": "./tsconfig.json",
"compilerOptions": {
"isolatedModules": false
}
}jest.config.js の globals へ ts-jest の tsconfig を設定します。
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
globals: {
"ts-jest": {
tsconfig: "./tsconfig.test.json",
},
},
};以上で TypeScript でテストが書けるようになった。
(WARN) Define ts-jest config under globals is deprecated. を解消する
jest を実行してみると以下の警告が表示されています。
yarn test
yarn run v1.22.19
$ jest
ts-jest[ts-jest-transformer] (WARN) Define `ts-jest` config under `globals` is deprecated. Please do
transform: {
<transform_regex>: ['ts-jest', { /* ts-jest config goes here in Jest */ }],
},
# ...globals に ts-jest の設定を書かないでとのことなのでスコープします。
module.exports = {
preset: "ts-jest",
testEnvironment: "node",
transform: {
"^.+\\.m?[tj]sx?$": [
"ts-jest",
{
tsconfig: "./tsconfig.test.json",
},
],
},
};参考: https://kulshekhar.github.io/ts-jest/docs/getting-started/options/
UI コンポーネントテスト用ライブラリ導入
以下のパッケージを導入します
yarn add -D jest-environment-jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-eventjest.config.js の testEnvironment を jest-environment-jsdom へ変更します。
module.exports = {
preset: "ts-jest",
testEnvironment: "jest-environment-jsdom",
transform: {
"^.+\\.m?[tj]sx?$": [
"ts-jest",
{
tsconfig: "./tsconfig.test.json",
},
],
},
};jest の設定ファイルを TypeScript 化
ts.config.json の include へ jest の設定ファイルを追加する。
diff --git a/tsconfig.json b/tsconfig.json
index ce6db6a..ae7d946 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,9 +1,9 @@
{
// ...
"exclude": ["node_modules"],
- "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
+ "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "./jest.setup.ts"]
}jest.setup.js のファイル形式を ts へ変更し CommonJS から ESModules へ書き換える。
export default {
clearMocks: true,
testEnvironment: "jest-environment-jsdom",
transform: {
"^.+\\.m?[tj]sx?$": [
"ts-jest",
{
tsconfig: "./tsconfig.test.json",
},
],
},
};セットアップファイルを用意する
各テストファイルで必ず import するライブラリを共通処理としてセットアップファイルに記述する。
export default {
clearMocks: true,
testEnvironment: "jest-environment-jsdom",
transform: {
"^.+\\.m?[tj]sx?$": [
"ts-jest",
{
tsconfig: "./tsconfig.test.json",
},
],
},
setupFilesAfterEnv: ["./jest.setup.ts"],
};import "@testing-library/jest-dom";
import React from "react";以上でプロジェクトへ Jest の導入をすることができました。