When using Vitest for testing, accessing environment variables from the .env file can be achieved through several methods. Below are detailed steps and examples:
1. Using the dotenv Library
First, ensure that the dotenv library is installed. This library helps load environment variables from the .env file into process.env.
Install dotenv:
bashnpm install dotenv
Use it in test files:
javascriptimport { describe, it, expect } from 'vitest'; import dotenv from 'dotenv'; dotenv.config(); // Load environment variables from the .env file describe('Test environment variables', () => { it('should be able to access environment variables', () => { const api_url = process.env.API_URL; expect(api_url).toBeDefined(); expect(api_url).toBe('https://api.example.com'); }); });
2. Using Vitest's Environment Variable Configuration
Vitest allows you to set environment variables directly in its configuration file. If you are using vitest.config.js, you can add environment variables in the configuration.
Edit vitest.config.js:
javascriptimport { defineConfig } from 'vitest/config'; export default defineConfig({ env: { API_URL: 'https://api.example.com', }, });
Use these environment variables in tests:
javascriptimport { describe, it, expect } from 'vitest'; describe('Test environment variables', () => { it('should be able to access environment variables from the configuration', () => { const api_url = process.env.API_URL; expect(api_url).toBe('https://api.example.com'); }); });
3. Combining dotenv with Automatic Loading
If you don't want to load dotenv repeatedly in each test file, you can configure automatic loading in vitest.config.js.
Update vitest.config.js:
javascriptimport { defineConfig } from 'vitest/config'; import dotenv from 'dotenv'; dotenv.config(); // Automatically load the .env file export default defineConfig({ // Other configurations... });
This way, Vitest automatically loads the .env file every time tests are run, so there's no need to call dotenv.config() in each test file.
Summary
The choice of method depends on your project requirements and personal preference. If your environment variables are primarily used for testing, setting them directly in the Vitest configuration may be more convenient. If the environment variables are also used by other parts of your application, using the dotenv library is more flexible.
I hope this helps you understand how to effectively manage and access environment variables in Vitest tests! If you have any questions, feel free to ask.