株式会社HAMWORKS
💻

Viteに諸々のテスト環境組み込んだ環境作る

2025/04/07に公開

いつ古くなるかわからないから毎回一応セットアップ方法は覗くようにしてるけど、ざっくりまとめておいたほうがいいなーと思ったので自分用メモ。

追加するのは以下のパッケージです

  • Vite (ESLintは一緒に入ってくるので一旦割愛)
  • Jest
  • Testing Library
  • Prettier
  • Husky
  • lint-staged

Viteのインストール

https://ja.vite.dev/

まずは普通にcreateコマンド叩きます。

npm create vite@latest
> npx
> cva

│
◇  Project name:
│  vite-project
│
◇  Select a framework:
│  React
│
◇  Select a variant:
│  TypeScript + SWC
│
◇  Scaffolding project in /path/to/vite-dev/vite-project...
│
└  Done. Now run:

  cd vite-project
  npm install
  npm run dev

Project nameは.でルート展開することのほうが多い(先にディレクトリ作ってたりするから)。

一旦やれよって言われてる

cd vite-project
npm i
npm run dev

をして、開発環境が動作するか確認します。

Jest + Testing Libraryをインストールする

Jest

Viteで使うなら多分Vitestのほうがいいんだろうけど、今回は使いません。

https://jestjs.io/ja/

TypeScriptを使うので、ts-jestも入れます。

https://kulshekhar.github.io/ts-jest/docs/getting-started/installation

npm install --save-dev jest typescript ts-jest @types/jest

jest.config.js は一部書き換えが必要です。

jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} **/
export default {
  testEnvironment: "jsdom",
  transform: {
    "^.+\.tsx?$": ["ts-jest", { tsconfig: 'tsconfig.app.json' }],
  },
};

transformのやつです。Viteがtsconfig分かれてるので指定し直しがいります。

Testing Library

次にTesting Library。
svelteは使わないので、@testing-library/sveltesvelte-jesterは一旦省きます。

https://testing-library.com/docs/svelte-testing-library/setup#jest

https://testing-library.com/docs/react-testing-library/intro

両方見て、必要なものだけインストール。

npm i --save-dev @testing-library/react @testing-library/dom @types/react @types/react-dom @testing-library/jest-dom jest-environment-jsdom

次に、jest-setup.tsの作成。書くのはインポート文1行。

import '@testing-library/jest-dom'

package.jsonのスクリプトにtestを追加します。ついでに、lint:fixのスクリプトも足しておきます(のちのち追加するlint-stagedで使う)
また、typemoduleにしておきます。ちょこちょこ記法でESMなの?CommonJSなの?って聞かれるので。(これないと大体AIがCommonJSに直してくる。あっても直すかもしれんけど)

package.json
{
  ...
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "lint": "eslint .",
+    "lint:fix": "eslint --fix",
    "preview": "vite preview",
+    "test": "jest"
  },
  ...
}

test:watchとかで、jest --watchをつけてもいいかも。私は都度自分で叩いてテスト実行する派なので一旦なしです。(今の所)

一旦テスト書いてみる

App.test.tsx
import { render, screen } from '@testing-library/react';
import App from './App';

test('renders Vite + React', () => {
  render(<App />);
  const element = screen.getByRole('heading', { name: 'Vite + React' });
  expect(element).toBeInTheDocument();
});

ちなみにApp.tsxはドシンプルに変えてます。

App.tsx
function App() {
  return (
    <>
      <h1>Vite + React</h1>
    </>
  )
}

export default App

テスト実行すると、テスト自体は通ります。が、toBeInTheDocumentに赤線(プロパティ 'toBeInTheDocument' は型 'JestMatchers<HTMLElement>' に存在しません。)が出てるので気になる。

npm test ./src/App.test.tsx

> vite-project@0.0.0 test
> jest ./src/App.test.tsx

ts-jest[config] (WARN) message TS151001: If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.
(node:9333) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 PASS  src/App.test.tsx
  ✓ renders Vite + React (27 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.561 s, estimated 1 s
Ran all test suites matching /.\/src\/App.test.tsx/i.

esModuleInteroptrueにしなね、って書いてあるのでtsconfig.app.jsonに追記します。

https://github.com/testing-library/jest-dom?tab=readme-ov-file#with-typescript

ドキュメント見てみると、tsconfigincludeも必要なよう。

tsconfig.app.json
{
  "compilerOptions": {
    ...

    "esModuleInterop": true,

    "types": ["jest", "@testing-library/jest-dom"]
  },
  "include": ["src", "jest-setup.ts"]
}

それだけだと赤線消えなかったので、typesも足してます。これで無事赤線も消えました!

Prettierのインストール

https://prettier.io/docs/install

npm install --save-dev --save-exact prettier

コンフィグファイルは好みの問題でprettier.config.jsにします。

prettier.config.js
// prettier.config.js, .prettierrc.js, prettier.config.mjs, or .prettierrc.mjs

/**
 * @see https://prettier.io/docs/configuration
 * @type {import("prettier").Config}
 */
const config = {
  trailingComma: 'es5',
  tabWidth: 2,
  semi: true,
  singleQuote: true,
  arrowParens: 'always',
};

export default config;

また、ESLintも使っているので併用できるようにeslint-config-prettierも入れます。

https://github.com/prettier/eslint-config-prettier#installation

npm i -D eslint-config-prettier

eslint.config.jsのextendsに追記します。

eslint.config.js
import js from "@eslint/js";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
+ import prettier from "eslint-config-prettier";

export default tseslint.config(
  { ignores: ["dist"] },
  {
    extends: [js.configs.recommended, ...tseslint.configs.recommended],
    files: ["**/*.{ts,tsx}"],
    languageOptions: {
      ecmaVersion: 2020,
      globals: globals.browser,
    },
    plugins: {
      "react-hooks": reactHooks,
      "react-refresh": reactRefresh,
    },
    rules: {
      ...reactHooks.configs.recommended.rules,
      "react-refresh/only-export-components": [
        "warn",
        { allowConstantExport: true },
      ],
    },
  },
+  prettier,
);

エディター側で保存時に自動的にPrettier走るようにはしてますが、一応スクリプトも追加。

package.json
{
  "name": "vite-project",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "tsc -b && vite build",
    "lint": "eslint .",
    "preview": "vite preview",
    "test": "jest",
+    "format": "prettier --write ./src/**/* --ignore-unknown"
  },
}

また、.prettierignoreも作成します。

public
*.d.ts

一旦はこの2つ。

Huskyとlint-stagedのインストール

Husky

https://typicode.github.io/husky/get-started.html

npm install --save-dev husky
npx husky init

あんましすることなくてお手軽でよきですね。

lint-staged

https://github.com/lint-staged/lint-staged

npm install --save-dev lint-staged

次に、Huskyのpre-commit内の記述を以下に書き換えます。

npx lint-staged

あとは、package.jsonにlint-stagedの記述を加えます。

package.json
{
  ...
+  "lint-staged": {
+    "*.{ts,tsx}": [
+      "npm run format",
+      "npm run lint:fix",
+      "npm run test -- ./src/"
+    ]
+  }
}

これで一旦開発環境作りは完了です。あとは作りたいものに合わせてパッケージ足したりLintのルール変えたりって感じかな?

株式会社HAMWORKS
株式会社HAMWORKS

Discussion