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

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

我想测试一下,比如:

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

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


当前回答

在Serhan C上扩展了一点。的答案……

根据博客文章如何用笑话测试安装dotenv -深入解释,你可以直接在setupFiles中包含“dotenv/config”,而不必创建和引用调用require(“dotenv”).config()的外部脚本。

也就是说,简单地去做

module.exports = {
    setupFiles: ["dotenv/config"]
}

其他回答

在Serhan C上扩展了一点。的答案……

根据博客文章如何用笑话测试安装dotenv -深入解释,你可以直接在setupFiles中包含“dotenv/config”,而不必创建和引用调用require(“dotenv”).config()的外部脚本。

也就是说,简单地去做

module.exports = {
    setupFiles: ["dotenv/config"]
}

我有最简单的实现env (specialtest .env)

require("dotenv").config({ path: './test.env' });
const { sum } = require('./sum.js');

describe('sum', () => {

  beforeEach(() => {
    jest.resetModules(); // remove cache
  })

  test('should success', () => {
    expect(sum(1, 3)).toEqual(4);
  })
})

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

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

import dotenv from "dotenv"
dotenv.config()

/* config options below */

当使用Typescript以下作品为我:

根: jest.config.js

/* eslint-disable @typescript-eslint/no-var-requires */ const {pathsToModuleNameMapper} = require('ts-jest'); const {compilerOptions} = require('./tsconfig.paths.json'); 模块。出口= { / /[…] moduleNameMapper: pathsToModuleNameMapper (compilerOptions。{prefix: '<rootDir>/'}), }; 的过程。env = Object.assign(进程。env, { env_name:“开发”, another_var:“abc123”, });

测试文件:

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

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

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

进来。/环境:

APP_PORT=8080