👏

Vite+React+TypeScript環境にJestとReact Testing Libraryを導入する

に公開

1.Jest, React Testing Libraryの導入

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

2.package.jsonにjestコマンドを追加

  "scripts": {
     # 略
    "test": "jest"
  },

3.configファイルを作成

以下のコマンドを打つ

npx ts-jest config:init

作成されたjest.config.jsに以下の記述を行う

export default {
  preset: 'ts-jest',
  testEnvironment: 'jest-environment-jsdom',
  moduleNameMapper: {
    '^@/(.*)$': '<rootDir>/src/$1',
  },
};

4.tsconfig.jsonを編集

{
  "compilerOptions": {
    # 略
    "esModuleInterop": true
  }
}

参考

https://typescriptbook.jp/tutorials/jest
https://kinosuke.hatenablog.jp/entry/2021/07/25/160300

Discussion