node.js 用 Jest 测试 process.env
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48033841/
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
test process.env with Jest
提问by Tomasz Mularczyk
I have an app that depends on environmental variables like:
我有一个依赖于环境变量的应用程序,例如:
const APP_PORT = process.env.APP_PORT || 8080;
and I would like to test that for example:
我想测试一下,例如:
- APP_PORT can be set by node env variable.
- or that an
expressapp is running on the port set withprocess.env.APP_PORT
- APP_PORT 可以由节点环境变量设置。
- 或者
express应用程序正在设置的端口上运行process.env.APP_PORT
How can I achieve this with Jest? Can I set these process.envvariables before each test or should I mock it somehow maybe?
我怎样才能用 Jest 做到这一点?我可以process.env在每次测试之前设置这些变量还是应该以某种方式模拟它?
回答by Tomasz Mularczyk
The way I did it can be found in this SO question.
我这样做的方式可以在这个 SO question 中找到。
It is important to resetModulesbefore each test and then dynamically import the module inside the test:
describe('environmental variables', () => {
const OLD_ENV = process.env;
beforeEach(() => {
jest.resetModules() // this is important - it clears the cache
process.env = { ...OLD_ENV };
delete process.env.NODE_ENV;
});
afterEach(() => {
process.env = OLD_ENV;
});
test('will receive process.env variables', () => {
// set the variables
process.env.NODE_ENV = 'dev';
process.env.PROXY_PREFIX = '/new-prefix/';
process.env.API_URL = 'https://new-api.com/';
process.env.APP_PORT = '7080';
process.env.USE_PROXY = 'false';
const testedModule = require('../../config/env').default
// ... actual testing
});
});
回答by zgreen
Jest's setupFilesis the proper way to handle this, and you need not install dotenv, nor use an .envfile at all, to make it work.
Jest'ssetupFiles是处理这个问题的正确方法,你不需要安装dotenv,也不需要使用任何.env文件来使它工作。
jest.config.js:
jest.config.js:
module.exports = {
setupFiles: ["<rootDir>/.jest/setEnvVars.js"]
};
.jest/setEnvVars.js:
.jest/setEnvVars.js:
process.env.MY_CUSTOM_TEST_ENV_VAR = 'foo'
That's it.
就是这样。
回答by Serhan C.
You can use setupFilesfeature of jest config. As documentation saidthat,
您可以使用setupFilesjest 配置的功能。正如文件所说,
A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file.Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself.
运行一些代码以配置或设置测试环境的模块的路径列表。每个 setupFile 将针对每个测试文件运行一次。由于每个测试都在其自己的环境中运行,因此这些脚本将在执行测试代码本身之前立即在测试环境中执行。
npm install dotenvdotenv that uses to access env variable.- Create your
.envfile to root directory of your application and add this line into it.
npm install dotenv用于访问 env 变量的 dotenv。- 将
.env文件创建到应用程序的根目录并将此行添加到其中。
#.env
APP_PORT=8080
- Create your custom module file as It name being someModuleForTest.js and add this line into it.
- 创建您的自定义模块文件,名称为 someModuleForTest.js 并将此行添加到其中。
//someModuleForTest.js
require("dotenv").config()
- Update your
jest.config.jsfile like this
jest.config.js像这样更新您的文件
module.exports = {
setupFiles: ["./someModuleForTest"]
}
- You can access env's variable within all test blocks.
- 您可以在所有测试块中访问 env 的变量。
test("Some test name", () => {
expect(process.env.APP_PORT).toBe("8080")
})
回答by Emi
In ./package.json:
在./package.json:
"jest": {
"setupFiles": [
"<rootDir>/jest/setEnvVars.js"
]
}
In ./jest/setEnvVars.js:
在./jest/setEnvVars.js:
process.env.SOME_VAR = 'value';
回答by jahller
Another option is to add it to the jest.config.jsfile after the module.exportsdefinition:
另一种选择是jest.config.js在module.exports定义后将其添加到文件中:
process.env = Object.assign(process.env, {
VAR_NAME: 'varValue',
VAR_NAME_2: 'varValue2'
});
This way it's not necessary to define the ENVvariables in each .specfile and they can be adjusted globally.
这样就不需要ENV在每个.spec文件中定义变量,它们可以全局调整。
回答by RobW
Depending on how you can organize your code, another option can be to put the env variable within a function that's executed at runtime.
根据组织代码的方式,另一种选择是将 env 变量放在运行时执行的函数中。
In this file, the env var is set at import time, and requires dynamic requires in order to test different env vars (as described in this answer):
在此文件中,环境require变量在导入时设置,并且需要 dynamic以测试不同的环境变量(如本答案所述):
const env = process.env.MY_ENV_VAR;
const envMessage = () => `MY_ENV_VAR is set to ${env}!`;
export default myModule;
In this file, the env var is set at envMessageexecution time, and you should be able to mutate process.env directly in your tests:
在这个文件中,env var 是在envMessage执行时设置的,你应该能够在你的测试中直接改变 process.env:
const envMessage = () => {
const env = process.env.MY_VAR;
return `MY_ENV_VAR is set to ${env}!`;
}
export default myModule;
Jest test:
玩笑测试:
const vals = [
'ONE',
'TWO',
'THREE',
];
vals.forEach((val) => {
it(`Returns the correct string for each ${val} value`, () => {
process.env.MY_VAR = val;
expect(envMessage()).toEqual(...
回答by andy
I think you could try this too:
我想你也可以试试这个:
const currentEnv = process.env;
process.env = { ENV_NODE: 'whatever' };
// test code...
process.env = currentEnv;
This works for me and you don't need module things
这对我有用,你不需要模块的东西
回答by Ismael Fdez
https://github.com/facebook/jest/blob/master/packages/jest-cli/bin/jest.js#L12-L14
https://github.com/facebook/jest/blob/master/packages/jest-cli/bin/jest.js#L12-L14
Find on node_module/jest-cli/bin/jest.js
在 node_module/jest-cli/bin/jest.js 上查找
#!/usr/bin/env node
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const importLocal = require('import-local');
if (!importLocal(__filename)) {
if (process.env.NODE_ENV == null) {
process.env.NODE_ENV = 'test';
}
require('../build/cli').run();
}

