javascript 使用 .env 文件通过 jest 进行单元测试

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50259025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:59:32  来源:igfitidea点击:

Using .env files for unit testing with jest

javascriptunit-testingenvironment-variablesjestjs

提问by Ronan Quigley

Is it possible to load environment variables from an env file for unit testing purposes in Jest? I'm looking to run a series of tests on it like so:

是否可以在 Jest 中从 env 文件加载环境变量以进行单元测试?我希望对其进行一系列测试,如下所示:

// unit tests for env file
describe('env', () => {
    it('should have a client id', () => {
        expect(process.env.CLIENT_ID).toBeDefined();
    });
    it('should have a client secret', () => {
        expect(process.env.CLIENT_SECRET).toBeDefined();
    });
    it('should have a host', () => {
        expect(process.env.HOST).toBeDefined();
    });
    it('should have a scope', () => {
        expect(process.env.SCOPE).toBeDefined();
    });
    it('should have a response type', () => {
        expect(process.env.RESPONSE_TYPE).toBeDefined();
    });
    it('should have a redirect uri', () => {
        expect(process.env.REDIRECT_URI).toBeDefined();
    });
});

Currently, all the above tests will fail, stating that the variables are undefined. Initially I was using a mocha/chai setup, which allowed me to just load all of my env variables via the use of dotenv. This involved running all unit tests through webpack and worked fine.

目前,上述所有测试都将失败,说明变量未定义。最初我使用的是 mocha/chai 设置,它允许我通过使用 dotenv 加载我所有的 env 变量。这涉及通过 webpack 运行所有单元测试并且工作正常。

However, from reading the documentationJest doesn't run tests through webpack; instead modules are mocked out via moduleNameMapper. This works fine for everything else, but I can't get the env file variables to load. So far I've tried using the setupFiles option to a js file that calls dotenv.config with the path of the env file given to it like so:

但是,从阅读文档来看,Jest 不会通过 webpack 运行测试;相反,模块是通过 moduleNameMapper 模拟出来的。这适用于其他一切,但我无法加载 env 文件变量。到目前为止,我已经尝试将 setupFiles 选项用于调用 dotenv.config 的 js 文件,其中包含 env 文件的路径,如下所示:

// setup file for jest
const dotenv = require('dotenv');
dotenv.config({ path: './env' });

This didn't work, so I've now resorted to using just a .env.js file for unit tests and passing this file into the setupFiles option instead. However, for maintainability, and to keep it working with webpack for production, I'd like to just keep it all in one file. Here's an extract of how the .env.js file looks for reference

这不起作用,所以我现在只使用 .env.js 文件进行单元测试,并将此文件传递给 setupFiles 选项。但是,为了可维护性,并保持它与 webpack 一起用于生产,我想将它全部保存在一个文件中。这是 .env.js 文件如何查找的摘录以供参考

// .env.js extract example
process.env.PORT = 3000;
process.env.HOST = 'localhost';
process.env.CLIENT_ID = 'your client id';
process.env.REDIRECT_URI = 'your callback endpoint';

采纳答案by li x

Your top config path using ./is relative from the point of injection, it's likely your test suite might be inside a folder named testwhich causes it to not be found when running your unit tests. dotenv.config();Uses global injection strategy which is similar to absolute pathing.

您使用的顶级配置路径./与注入点相对,您的测试套件可能位于名为的文件夹中test,这会导致在运行单元测试时找不到它。dotenv.config();使用类似于绝对路径的全局注入策略。

回答by The Coder

None of these worked for me, but I found a great article on configuring dotenv by default in Jestin the package.json:

这些都不适合我,但我在 package.json 中找到了一篇关于在 Jest默认配置 dotenv的很棒的文章:

{
  "scripts": {
    "test": "jest --setupFiles dotenv/config"
  }
}

回答by Ronan Quigley

So the issue require changing this:

所以这个问题需要改变这个:

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

to :

到 :

dotenv.config();

Why it didn't pick it up I have no idea, but just leaving the defaults worked.

为什么它没有捡起来我不知道,但只是保留默认值。

回答by Joey587

I am little late, but hope this helps for someone who are looking for making dotenv work. This is just an extended flavor of what @DavidDehghan said. So add a setup file to be run before any jest configuration like as David said

我有点晚了,但希望这对正在寻找使 dotenv 工作的人有所帮助。这只是@DavidDehghan 所说内容的延伸。因此,添加一个要在任何玩笑配置之前运行的安装文件,就像大卫所说的

Now making sure dotenv load for the platform to resolve the relative path, please make use of pathmodule to resolve the folder

现在确保平台加载dotenv来解析相对路径,请使用path模块来解析文件夹

import * as  dotenv from 'dotenv';
import * as path from 'path';

dotenv.config({ path: path.resolve(__dirname + './../config/testFolder/.env') });

Now in your spec file you can test if the process.envvariable contains the values loaded from .envfile in testFolder

现在在您的规范文件中,您可以测试process.env变量是否包含从.env文件中加载的值testFolder

describe('Test suite - testing app service', () => {
  beforeAll(() => {
    console.log('coming inside beforeAll', process.env.LCp);

  });
});

回答by David Dehghan

You can load the env files for all your tests like this. The setup file will be executed once per each test file that is loaded.

您可以像这样为所有测试加载 env 文件。每个加载的测试文件都会执行一次安装文件。

jest.config.js : 

module.exports = {
 ....
    setupFiles: ["<rootDir>/test/setup-tests.ts"]
}


test/test-setup.ts:

import dotenv from 'dotenv';
dotenv.config({path: './config.env.test'});