如何在Jest单元测试中加载.env文件中的环境变量?
Absolutely! You can load environment variables from a .env file in Jest tests—your earlier attempt with setupFiles and dotenv didn't work likely due to a small path issue or missing setup steps. Let's walk through the correct way to get this working, so you can keep using a single .env file for both your production webpack setup and Jest tests.
Step 1: Install dotenv (if you haven't already)
First, make sure dotenv is installed as a dev dependency:
npm install dotenv --save-dev # or yarn add dotenv -D
Step 2: Configure your Jest setup file
Create a setup file (e.g., jest.setup.js in your project root) with the following code:
const dotenv = require('dotenv'); // Load the .env file from your project root // Adjust the path if your .env file is in a different location dotenv.config({ path: './.env' });
Then, tell Jest to use this setup file by adding it to your Jest configuration. You can do this in either jest.config.js:
module.exports = { setupFiles: ['./jest.setup.js'], // Add any other Jest config options you need here };
Or directly in your package.json:
{ "jest": { "setupFiles": ["./jest.setup.js"] } }
Why your initial setup failed
The most common issue here is a path mistake:
- You wrote
path: './env'in your setup file, but standard.envfiles have a leading dot (.env). Double-check your filename and path. - If your setup file lives in a subdirectory (e.g.,
tests/jest.setup.js), you'll need to adjust the path to../.envto target the project root.
Bonus: Environment-specific .env files
If you need separate env vars for testing (e.g., .env.test), just update the path in the setup file:
dotenv.config({ path: './.env.test' });
Alternatively, you can use dotenv-cli to load the env file directly in your test script (install it first with npm install dotenv-cli --save-dev):
{ "scripts": { "test": "dotenv -e .env.test jest" } }
Once you've got this setup right, your existing test cases will start passing—process.env.CLIENT_ID, process.env.CLIENT_SECRET, and all your other env vars will be defined just like they are in your webpack setup. No more maintaining separate .env.js files!
内容的提问来源于stack exchange,提问作者Ronan Quigley

