用 Jest 测试 process.env [英] Test process.env with Jest

查看:29
本文介绍了用 Jest 测试 process.env的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an application that depends on environmental variables like:

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

我想测试一下,例如:

  • APP_PORT 可以由 Node.js 环境变量设置.
  • 或者 Express.js 应用程序正在使用 process.env.APP_PORT
  • APP_PORT can be set by a Node.js environment variable.
  • or that an Express.js application is running on the port set with process.env.APP_PORT

如何使用 Jest 实现这一目标?我可以在每次测试之前设置这些 process.env 变量还是应该以某种方式模拟它?

How can I achieve this with Jest? Can I set these process.env variables before each test or should I mock it somehow maybe?

推荐答案

我的做法 可以在这个 StackOverflow 问题中找到.

在每次测试之前使用 resetModules 很重要,然后动态地使用在测试中导入模块:

It is important to use resetModules before each test and then dynamically import the module inside the test:

describe('environmental variables', () => {
  const OLD_ENV = process.env;

  beforeEach(() => {
    jest.resetModules() // Most important - it clears the cache
    process.env = { ...OLD_ENV }; // Make a copy
  });

  afterAll(() => {
    process.env = OLD_ENV; // Restore old environment
  });

  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
  });
});

如果您想在运行 Jest 之前寻找一种加载环境值的方法,请查看下面的答案.您应该为此使用 setupFiles.

If you look for a way to load environment values before running the Jest look for the answer below. You should use setupFiles for that.

这篇关于用 Jest 测试 process.env的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆