Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access my .env variables from a Vitest test?

I am trying to migrate my tests from Jest to Vitest. I have a test suite that uses the dotenv package to pull in my .env variables.

I have this in my test suite

beforeAll(async () => {
        vi.clearAllMocks();
        cleanUpMetadata();
        dotenv.config();
        controller = new UserController(container.get<UserServiceLocator>(Symbol.for("UserServiceLocator")),
            container.get<EmailServiceLocator>(Symbol.for("EmailServiceLocator")));
    });

and this is the code in the test that has the undefined variable:

let requestObj = httpMocks.createRequest({
            cookies: {
                token: jwt.sign({ username: "testusername" }, process.env.JWT_SECRET_KEY!)
            }
        });

Is there something special to Vitest that I have to do in order to get my .env variables to be accessible?

like image 989
Bebet Avatar asked Aug 31 '25 16:08

Bebet


2 Answers

You can include the dotenv package(if thats what you are using) into the vitest.config.ts file, it will look something like this below:

import { defineConfig } from 'vitest/config';
import { resolve } from 'path';

export default defineConfig({
  root: '.',
  esbuild: {
    tsconfigRaw: '{}',
  },
  test: {
    clearMocks: true,
    globals: true,
    setupFiles: ['dotenv/config'] //this line,
  },
  resolve: {
    alias: [{ find: '~', replacement: resolve(__dirname, 'src') }],
  },
});
like image 85
Patrick Kabwe Avatar answered Sep 02 '25 15:09

Patrick Kabwe


For whoever lands here after removing the dotenv lib because Node v20.6.0+ handles .env files automatically, just use the loadEnv function from vite in your vitest.config.ts:

import { loadEnv } from 'vite';
import { defineConfig } from 'vitest/config';

export default defineConfig(({ mode }) => ({
    test: {
        // mode defines what ".env.{mode}" file to choose if exists
        env: loadEnv(mode, process.cwd(), ''),
    },
}));

Provided you use a default .env file.

like image 20
c4k Avatar answered Sep 02 '25 17:09

c4k