— tech notes — 1 min read
2024-07-03
While writing test case, I needed to set environment variables for Jest. I don't want to setup dotenv in the spec.
This setup ensures that environment variables from a .env
file are loaded before running Jest tests:
package.json
: Modify the test script to run jest
.dotenv
: Add the dotenv
package to manage environment variables.jest.config.js
: Load environment variables by requiring dotenv
in the Jest configuration file..env
file: Place your environment variables in a .env
file in the project root.Update package.json
:
1"scripts": {2 "test": "jest"3}
Install dotenv
:
1npm install dotenv
Create jest.config.js
:
1require('dotenv').config();2
3module.exports = {4 // Jest config options5};
Ensure .env
file is in the project root.