LoginSignup
15
4

More than 1 year has passed since last update.

Jestでdotenvを使う

Last updated at Posted at 2019-07-31

Jestでdotenvが動かなかった

Jestを利用したときに、dotenv周りで苦戦しました。日本語の記事が見当たらなかったので、忘れない内に対処法を記載します。

dotenvとは

dotenvは、 .env ファイルの内容を環境変数としてNode.jsで読み込むためのnpmパッケージです。
npm - dotenv

詳しい使い方はこちらが非常に参考になりました。
環境変数の代わりに .env ファイルを使用する (dotenv)

Jestとは

JestはJavaScript向けのテストフレームワークです。
Jest公式サイト

Jestでdotenvが動かなかった

Jestでテストコードを実行した時に、以下のコードが動作しませんでした。

import dotenv from 'dotenv'

// .envファイルの値を読み込んでオブジェクトに代入する
const config = dotenv.config().parsed;

package.jsonに設定を追加する

対処法を探したところ、以下の記事を見つけました。
Using dotenv with Jest

package.jsonに以下の項目を追加すればよいそうです。

{
  "jest": { 
    "setupFiles": [
      "dotenv/config"
    ]
  } 
}

試したところ、うまくいきました。

さいごに

無事に解決してよかったです。以下の記事を参考にさせていただきました。

15
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
4