简体   繁体   English

NODE_ENV 与 Jest

[英]NODE_ENV with Jest

I am migrating from Mocha to Jest.我正在从 Mocha 迁移到 Jest。 My test imports the config package, which selects a configuration file or another depending on the NODE_ENV environment variable.我的测试导入config package,它根据NODE_ENV环境变量选择一个或另一个配置文件。 However, it looks like NODE_ENV is found while running the test from Jest但是,看起来在从 Jest 运行测试时发现了NODE_ENV

Next line does not work (that is, NODE_ENV is ignored):下一行不起作用(即忽略NODE_ENV ):

 NODE_ENV=test jest test/*.js --notify --config jest.config.json

As a consequence the config package reports:因此config package 报告:

console.error node_modules/config/lib/config.js:1727
WARNING: NODE_ENV value of 'test' did not match any deployment config file names. 

Do you know how to include NODE_ENV ?你知道如何包含NODE_ENV吗?

Jest automatically defines environment variable NODE_ENV as test (see https://jestjs.io/docs/en/getting-started.html ), as you can confirm from your error message: Jest会自动将环境变量NODE_ENV定义为test (请参阅https://jestjs.io/docs/en/getting-started.html ),您可以从错误消息中进行确认:

console.error node_modules/config/lib/config.js:1727
WARNING: NODE_ENV value of 'test' did not match any deployment config file names. 

What you can do is simply create config/test.json and include the contents {} , which is an empty valid JSON object. 您可以做的就是简单地创建config / test.json并包含内容{} ,这是一个空的有效JSON对象。

See https://github.com/lorenwest/node-config/wiki/Strict-Mode 参见https://github.com/lorenwest/node-config/wiki/Strict-Mode

Note : the aforementioned error occurs when you use the config package, and meanwhile you don't have the test.json file in the config directory. 注意 :当您使用config软件包时,发生上述错误,同时config目录中没有test.json文件。

The easiest way is using cross-env package:最简单的方法是使用cross-env package:

npm install --save-dev cross-env

Then, you can use it in your package.json :然后,您可以在您的package.json中使用它:

"scripts": {
    "test": "cross-env NODE_ENV=development jest --config jest.config.json"
}

The warning is from the Strict-Mode.警告来自严格模式。 So what you have to do here is..所以你在这里要做的是..

  1. Create a file called test.json inside config/config/中创建一个名为test.json的文件
  2. Add NODE_ENV value as test添加NODE_ENV值作为test

That should work那应该工作

Please create test.js in the config folder:请在配置文件夹中创建test.js

module.exports = {};

and then add dotenv-cli as devDependencies然后将dotenv-cli添加为 devDependencies

dotenv -e .env -- jest --maxWorkers=50% --watch

Note: jest automatically set NODE_ENV=test注意: jest自动设置NODE_ENV=test

You can add this to your babel config: 您可以将其添加到您的babel配置中:

"env": {
  "test": {
    "presets": [["env"], ...<OTHER PRESETS>]
  }
}

This should also automatically set NODE_ENV=test when running jest . 运行jest时,这还应该自动设置NODE_ENV=test

More info here: Getting Started - Jest 更多信息在这里: 入门-Jest

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM