Open3

next.jsでユニットテスト書く練習する

西島ボルバルザーク健吾西島ボルバルザーク健吾

環境セットアップ

インストール

next.jsのインストールは公式の通り。

npx create-next-app@latest

npmパッケージ

npm install --save-dev jest @testing-library/react @testing-library/jest-dom @testing-library/user-event ts-jest
# npm testで動作しなかったので調べたら下記が足りなかった
npm install --save-dev jest-environment-jsdom
npm install --save-dev @types/jest

設定ファイル

https://zenn.dev/ohimusdev46301/articles/8bdcd8f75d87b1
上記サイト見てglobals追加したけど、なんかdeprecatgedだったので下記のようなtransform付近のコードに変換した。

jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'jsdom',
    setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
    transform: {
	'^.+\\.(ts|tsx)$': ['ts-jest', {
            tsconfig: '<rootDir>/tsconfig.test.json'
	}],
    },
};

tsconfig.json
{
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
  "exclude": ["node_modules"]
}
tsconfig.test.json
{
  "extends": "./tsconfig.json",
  "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
  "exclude": ["node_modules"],
  "baseUrl": ".",
  "compilerOptions": {
    "jsx": "react-jsx"
  },
  "paths": {
    "@/*": ["./src/*"]
  }
}

```json:package.json
{
  "name": "app",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "test": "jest"
  },
  "dependencies": {
    "next": "14.2.13",
    "react": "^18",
    "react-dom": "^18"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^6.5.0",
    "@testing-library/react": "^16.0.1",
    "@testing-library/user-event": "^14.5.2",
    "@types/jest": "^29.5.13",
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "eslint": "^8",
    "eslint-config-next": "14.2.13",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "ts-jest": "^29.2.5",
    "typescript": "^5"
  }
}

とりまこれでテストは動いた。

参考サイト

https://zenn.dev/ohimusdev46301/articles/8bdcd8f75d87b1
https://zenn.dev/keita_hino/articles/488d31e8c4a240