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

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

问题描述

我有一个依赖于以下环境变量的应用程序:

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可以通过节点env变量设置.
  • express应用程序正在使用process.env.APP_PORT
  • 设置的端口上运行
  • APP_PORT can be set by node env variable.
  • or that an express app 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?

推荐答案

我的操作方式在每次测试之前 resetModules 非常重要,然后动态导入测试中的模块:

It is important to resetModules before 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
  });
});

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

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