我有一个依赖于环境变量的应用程序,例如:
const APP_PORT = process.env.APP_PORT || 8080;
我想测试一下,例如:
- APP_PORT 可以由 Node.js 环境变量设置。
- 或者那个 Express.js应用程序正在使用
process.env.APP_PORT
设置的端口上运行
如何使用 Jest 实现这一目标?我可以在每次测试之前设置这些 process.env
变量还是应该以某种方式模拟它?
最佳答案
我的做法can be found in this Stack Overflow question .
使用 resetModules 很重要在每次测试之前,然后在测试中动态导入模块:
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 之前寻找一种加载环境值的方法,请查找 answer below .您应该使用 setupFiles为此。
关于node.js - 用 Jest 测试 process.env,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48033841/