我有一个应用程序,它依赖于环境变量,如:
const APP_PORT = process.env.APP_PORT || 8080;
我想测试一下,比如:
APP_PORT可以通过Node.js环境变量设置。 或者Express.js应用程序运行在process.env.APP_PORT的端口集上
我如何用Jest实现这一点?我可以设置这些流程吗?env变量之前每个测试或我应该以某种方式模拟它可能?
我有一个应用程序,它依赖于环境变量,如:
const APP_PORT = process.env.APP_PORT || 8080;
我想测试一下,比如:
APP_PORT可以通过Node.js环境变量设置。 或者Express.js应用程序运行在process.env.APP_PORT的端口集上
我如何用Jest实现这一点?我可以设置这些流程吗?env变量之前每个测试或我应该以某种方式模拟它可能?
当前回答
Jest的setupFiles是处理这个问题的正确方法,并且您不需要安装dotenv,也不需要使用.env文件来使其工作。
jest.config.js:
module.exports = {
setupFiles: ["<rootDir>/.jest/setEnvVars.js"]
};
jest / setEnvVars . js:
process.env.MY_CUSTOM_TEST_ENV_VAR = 'foo'
就是这样。
其他回答
在我看来,如果您将环境变量的检索提取到一个实用程序中(如果没有设置环境变量,您可能希望包含一个快速失败的检查),那么您就可以模拟该实用程序,这样会更清晰、更容易理解。
// util.js
exports.getEnv = (key) => {
const value = process.env[key];
if (value === undefined) {
throw new Error(`Missing required environment variable ${key}`);
}
return value;
};
// app.test.js
const util = require('./util');
jest.mock('./util');
util.getEnv.mockImplementation(key => `fake-${key}`);
test('test', () => {...});
我的方法可以在这个Stack Overflow问题中找到。
在每次测试之前使用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之前寻找加载环境值的方法,请参见下面的答案。你应该使用setupFiles。
我有最简单的实现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);
})
})
测试文件:
const APP_PORT = process.env.APP_PORT || 8080;
在./package.json的测试脚本中:
"scripts": {
"test": "jest --setupFiles dotenv/config",
}
进来。/环境:
APP_PORT=8080
在Serhan C上扩展了一点。的答案……
根据博客文章如何用笑话测试安装dotenv -深入解释,你可以直接在setupFiles中包含“dotenv/config”,而不必创建和引用调用require(“dotenv”).config()的外部脚本。
也就是说,简单地去做
module.exports = {
setupFiles: ["dotenv/config"]
}