How to Mock dotenv
in Jest: A Senior Developer’s Guide
If you’ve ever used the dotenv
library in a Node.js project, you know how useful it is for loading environment variables from a .env
file. But what happens when you want to mock dotenv
in Jest for unit testing?
In this article, I’ll walk you through the correct way to mock dotenv
using Jest, explain why you might want to do this, and provide clean, production-quality examples.
📌 Why Mock dotenv
in Jest?
When writing unit tests, especially for backend services, you often want to avoid loading real environment variables. Maybe you want to simulate different values for process.env
, or just avoid any .env
side effects altogether.
Mocking dotenv
allows you to:
- Prevent external dependencies from interfering with tests
- Inject specific
process.env
values - Increase test speed and isolation
Let’s get to it.
🔧 How to Mock dotenv
with Jest
1. Install Dependencies
If you haven't already:
npm install dotenv --save
npm install jest --save-dev
2. The Code Under Test
Assume this is your app code (config.js
):
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
port: process.env.PORT || 3000,
};
3. Mocking dotenv
in Jest
Create a test file config.test.js
:
jest.mock('dotenv', () => ({
config: jest.fn(() => {
process.env.PORT = '5000'; // mock your env values here
return { parsed: { PORT: '5000' } };
}),
}));
const config = require('./config');
describe('Config Module', () => {
it('should return mocked port value', () => {
expect(config.port).toBe('5000');
});
});
✅ What This Does:
- Mocks the
config()
function fromdotenv
- Sets
process.env.PORT
to a test value - Avoids calling the real
.env
file on disk
🧠 Pro Tips for Senior Developers
- Keep your
.env
mocking logic isolated per test file - Use
beforeEach
orafterEach
to resetprocess.env
if needed - Don’t mock
dotenv
globally unless you're writing integration tests with custom runners
🏁 Conclusion
Mocking dotenv
in Jest is a clean and effective way to control your test environment and keep your unit tests predictable. By avoiding file system dependencies and setting process.env
directly, you can write faster and more reliable tests.