我有一个取决于环境变量的应用程序,例如:
const APP_PORT = process.env.APP_PORT || 8080;
我想测试例如:
express
process.env.APP_PORT
我如何用Jest做到这一点?我可以process.env在每次测试之前设置这些变量,还是应该以某种方式模拟它?
process.env
在每次测试之前重设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 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之前寻找一种加载env值的方法,请寻找以下答案。您应该为此使用setupFiles。