我有一个应用程序,它依赖于环境变量,如:

const APP_PORT = process.env.APP_PORT || 8080;

我想测试一下,比如:

APP_PORT可以通过Node.js环境变量设置。 或者Express.js应用程序运行在process.env.APP_PORT的端口集上

我如何用Jest实现这一点?我可以设置这些流程吗?env变量之前每个测试或我应该以某种方式模拟它可能?


当前回答

根据@HenryTipantuña的建议,在jest.config.js中导入dotenv,并使用.env。config路径下的Test文件

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

其他回答

您可以使用Jest配置的setupFiles特性。文档上说过,

运行要配置或设置的代码的模块的路径列表 测试环境。每个setupFile将在每个测试中运行一次 文件。因为每个测试都在自己的环境中运行,所以这些脚本会 在执行之前立即在测试环境中执行 测试代码本身。

npm install dotenv dotenv that uses to access environment variable. Create your .env file to the root directory of your application and add this line into it: #.env APP_PORT=8080 Create your custom module file as its name being someModuleForTest.js and add this line into it: // someModuleForTest.js require("dotenv").config() Update your jest.config.js file like this: module.exports = { setupFiles: ["./someModuleForTest"] } You can access an environment variable within all test blocks. test("Some test name", () => { expect(process.env.APP_PORT).toBe("8080") })

另一种选择是将其添加到模块之后的jest.config.js文件中。出口的定义:

process.env = Object.assign(process.env, {
  VAR_NAME: 'varValue',
  VAR_NAME_2: 'varValue2'
});

这样就不需要在每个.spec文件中定义环境变量,并且可以全局调整它们。

如果使用require("dotenv"),以上所有方法都有效。这是一个没有TypeScript的NodeJS应用程序,如Jialx或Henry Tipantuna所建议的那样。

但如果你在使用ts-jest并且在jest。config。ts文件中。

import dotenv from "dotenv"
dotenv.config()

/* config options below */

测试文件:

const APP_PORT = process.env.APP_PORT || 8080;

在./package.json的测试脚本中:

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

进来。/环境:

APP_PORT=8080

我觉得你也可以试试这个:

const currentEnv = process.env;
process.env = { ENV_NODE: 'whatever' };

// test code...

process.env = currentEnv;

这适用于我,你不需要模块的东西