[React.js]jestとjest-html-reportersの導入

[React.js]jestとjest-html-reportersの導入

create-react-appで作成したReactプロジェクトではデフォルトでtestスクリプトはreact-scriptsが設定されています。

テストの実行形式をjestに変更し、なおかつtestの結果をhtmlで出力できるjest-html-reportersの導入をします。

導入

パッケージのインストール

React testに有効なEnzymeとその関連パッケージ、jest-html-reportersをインストールします。

yarn add -D @types/enzyme enzyme @types/enzyme-adapter-react-16 enzyme-adapter-react-16 ts-jest
yarn add -D jest-html-reporters

package.jsonの修正

  • test scriptをreact-scriptsからjestに変更
  • jestの関連設定を追加
  • jest-html-reportersの設定を追加
  {
    ...
    "scripts": {
      "test": "dotenv -e ../../env/.env.test jest",
    },
    "jest": {
      "preset": "ts-jest",
      "globals": {
        "ts-jest": {
          "tsconfig": "tsconfig.json"
        }
      },
      "moduleNameMapper": {
        "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
        "\\.(css|less|scss|sass)$": "identity-obj-proxy",
        "src(.*)":"<rootDir>/src/$1",
        
        ---- ↓ monorepo環境にて共通モジュールの読み込みがある場合は設定する↓----
        "@common/(.*)":"<rootDir>/../common/src/$1"
        ---- ↑ ----
      },
      "reporters": [
        "default",
        [
          "jest-html-reporters",
          {
            "hideIcon": true,
            "pageTitle": "UT test report",
            "publicPath": "./testreport",
            "filename": "report.html",
            "expand": true
          }
        ]
      ],
      "snapshotSerializers": [
        "enzyme-to-json/serializer"
      ],
      "setupFilesAfterEnv": [
        "<rootDir>/src/setupEnzyme.ts"
      ],
    }
    ...
  }

fileMock.jsの作成

projectの下にfileMock.jsを作成します。

画像ファイルや動画ファイルのモックをしてくれます。

//__mocks__/fileMock.js
module.exports = 'test-file-stub';

setupEnzyme.tsの作成

Enzymeの設定ファイルを作成します。

// src/setupEnzyme.ts
import { configure } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16';
configure({ adapter: new EnzymeAdapter() });

最終的なディレクトリ構造

project/
 ├ __mocks__/
 │ └ fileMock.js
 ├ src/
 │ ├ App.tsx
 │ ├ App.test.tsx
 │ └ setupEnzyme.ts
 └ package.json

実行

yarn test

jest-html-reportersによって、testreport/report.htmlが出力されます。

関連

[React.js]monorepo環境を構築する+typescript

[React.js]dotenvを利用して環境差分を吸収する

参考

jest-html-reporters

React.jsカテゴリの最新記事