フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

Nuxtjs+typescriptにjestを設定する

Summary

  • nextjs+typescript環境にjestをインストールする機会があったので、設定した手順をメモしておく。

install

npm install @nuxtjs/dotenv
npm install --save-dev jest @types/jest  ts-jest

setting

  • package.jsonファイルに下記の記述を追記する
  "scripts": {
      ...,
     "test": "jest --runInBand"
      ...,
  }
  • app/tsconfig.jsonファイルに下記の記述を追加する
"compilerOptions": {
    ...,
    "types": ["...", "@types/jest"],
    ....
  },

jestの初期化

  • jest.js --initをコマンドを実行する
 ./node_modules/jest/bin/jest.js --init
  • 「構成ファイルにTypescriptを使用しますか? ›(y / N)」と聞かれるので、ここはyesと入力して下さい。
 ? Would you like to use Typescript for the configuration file? › (y/N)
  • nodeを選択する
? Choose the test environment that will be used for testing › - Use arrow-keys. Return to submit.
❯   node
    jsdom (browser-like)
  • 「? Jestにカバレッジレポートを追加しますか? ›(y / N)」と聞かれるので、やっぱりyesと入力して下さい。
? Do you want Jest to add coverage reports? › (y/N) ←レポートが欲しければ y
  • 「?カバレッジ用のコードを計測するためにどのプロバイダーを使用する必要がありますか? 」と聞かれているので、とりあえず「v8」を選択する
? Which provider should be used to instrument code for coverage? › - Use arrow-keys. Return to submit.
❯   v8
    babel

(参考文献)※nodeのバージョンが14のため、v8を選択する

https://jestjs.io/ja/docs/configuration#coverageprovider-string

  • 「?すべてのテストの間にモックコールとインスタンスを自動的にクリアしますか? ›(y / N)」と聞かれているので、「N」を選択する
? Automatically clear mock calls and instances between every test? › (y/N) 

上記の設定を手順を行うと「jest.config.ts」にファイルが作成される

jest.config.tsファイルの設定

(変更前)
  // preset: undefined,
(変更後)
  preset: "ts-jest",

(変更前)
  // setupFiles: [],
(変更後)
  setupFiles: ["/root/tests/setup-tests.ts"],

(変更前)
  // globals: {},
(変更後)
  globals: {
    'ts-jest': {
        isolatedModules: true
    }
  },

(変更前)
  // collectCoverageFrom: undefined,
(変更後)
  collectCoverageFrom: [
    '**/*.{ts,tsx}',
    '!**/*.d.ts',
    "!**/node_modules/**",
    "!**/vendor/**"
  ],
  • `tests/setup-tests.ts'ファイルを作成する。上記の作成した.envファイルを読み込む
import dotenv from 'dotenv';

dotenv.config({ path: '.env' });

(参考文献)

https://stackoverflow.com/questions/50259025/using-env-files-for-unit-testing-with-jest https://www.adoclib.com/blog/access-process-env-property-when-testing-nuxt-js-app-with-jest.html

Test execution command

npm test