6

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?

Bebet
  • 199
  • 2
  • 12

4 Answers4

8

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') }],
  },
});
Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96
Patrick Kabwe
  • 81
  • 1
  • 3
1
import.meta.env.%VARIABLE_NAME%

Got it from here: https://stackoverflow.com/a/70711231

0

vitest will automatically load your .env file(s) from the project root directory, which probably isn't the same directory as your test files. Your file structure might look something like this:

 project
   .env
   package.json
   vite.config.json
   src/
     myCode.js
   test/
     myCode.test.js

In node, you access a variable using import.meta.env.VITE_MY_VARIABLE_NAME. In HTML, use the special syntax %VITE_MY_VARIABLE_NAME%.

If you're still getting undefined variables, add the VITE_ prefix to your variable name, which tells vite the value is safe to expose.

Matt
  • 3,793
  • 3
  • 24
  • 24
-1

In Node.js Assuming you want to access your env variable VAR you should prefix it with VITE_ like:

VITE_VAR=123

then you can access it regularly with process.env.VITE_VAR

Eli Zatlawy
  • 678
  • 10
  • 24