在JEST中使用dotenv路径 [英] using dotenv path with JEST

查看:249
本文介绍了在JEST中使用dotenv路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试在Jest测试中使用其他.env文件,但到目前为止我无法使其正常工作.

I'm trying to use a different .env file for my Jest tests, but so far I couldn't make it work.

package.json:

{
  "name": "task-manager",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "module": "main.js",
  "scripts": {
    "start": "node -r esm src/index.js",
    "dev": "nodemon -r esm -r dotenv/config src/index.js dotenv_config_path=./config/.env",
    "test": "jest --setupFiles dotenv/config --watch"
  },
  "jest": {
    "testEnvironment": "node"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@sendgrid/mail": "^6.3.1",
    "bcryptjs": "^2.4.3",
    "dotenv": "^6.2.0",
    "esm": "^3.2.10",
    "express": "^4.16.4",
    "jest": "^24.3.1",
    "jsonwebtoken": "^8.5.0",
    "mongodb": "^3.1.13",
    "mongoose": "^5.4.17",
    "multer": "^1.4.1",
    "sharp": "^0.21.3",
    "supertest": "^4.0.0",
    "validator": "^10.11.0"
  },
  "devDependencies": {
    "@babel/core": "^7.3.4",
    "@babel/preset-env": "^7.3.4",
    "babel-jest": "^24.3.1"
  }
}

每次我运行npm测试时,使用的MONGODB_URL都存储在我的.env文件中,而不是我的test.env文件中

Every time I ran my npm test, the MONGODB_URL used was the stored in my .env file, instead of my test.env file

我创建了一个配置文件夹来存储我的.env开发文件以避免这种情况,但是现在我的应用程序在运行Jest时不再使用env vars.

I created a config folder to store my .env dev file to avoid this, but now my app doesn't use the env vars when I run the Jest.

我在开发脚本中设置了配置路径,但是我无法用Jest做同样的事情.

I setup a config path in my dev script, but I couldn't do the same with Jest.

预期的行为:我只想对Jest使用不同的MONGODB_URL进行测试.

Expected behavior: I just want to use a different MONGODB_URL for my tests with Jest.

推荐答案

您必须明确指定dotenv软件包应使用哪个.env.

You have to explicitly specify which .env should be used by the dotenv package.

在您的dotenv/config.js文件(用作笑话的安装文件)的第一行中,添加以下内容:

In your dotenv/config.js file which is used as a setup file for jest on the very first line add this:

require('dotenv').config({ path: './test.env' })

这篇关于在JEST中使用dotenv路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆