Fukuemon / MeAR

3Dで見るグルメアプリのフロントエンド
https://mear.vercel.app
0 stars 0 forks source link

Jestとtesting-libraryの設定#19 #23

Closed Fukuemon closed 11 months ago

Fukuemon commented 11 months ago

1. 必要なパッケージのインストール

テスト用のライブラリの他に、jestのコンパイルのためのパッケージとAPIの型定義ファイルもまとめてinstall

npm install --save-dev jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom @testing-library/user-event ts-jest @types/jest

2. jestの設定

jest.config.js

const nextJest = require('next/jest')

const createJestConfig = nextJest({
  dir: './'
})

/** @type {import('jest').Config} */
const config = {
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], //setup.jsを読み込むように(別途用意)
  preset: 'ts-jest', // TypeScriptのコンパイル用のパッケージ
  testEnvironment: 'jest-environment-jsdom',

  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1'
  }
}

module.exports = createJestConfig(config)

jest.setup.js

import '@testing-library/jest-dom'

3. tsconfigの修正

typesを追加

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
+    "types": ["node", "jest", "@testing-library/jest-dom"],
    "allowJs": true,
    "skipLibCheck": true,

4. babelの設定

test実行時にjsxファイルをコンパイルできないみたいなエラーが出るため、babelの設定を行う(理解が曖昧) baberのpresetをインストール

npm i @babel/preset-react @babel/preset-typescript

設定ファイルを追加 .babelrc

{
  "presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"]
}

5. eslintのplugin追加

npm i eslint-plugin-jest-dom eslint-plugin-testing-library

.eslintrc.jsに設定を追加

module.exports = {
  root: true,
  extends: [
    'plugin:@typescript-eslint/recommended',
    'next/core-web-vitals',
    'prettier',
    'plugin:tailwindcss/recommended',
    'plugin:storybook/recommended'
  ],
+  plugins: ['unused-imports', 'testing-library', 'jest-dom'],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: './tsconfig.json'
vercel[bot] commented 11 months ago

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
mear ✅ Ready (Inspect) Visit Preview Oct 22, 2023 11:23am