Skip to content

Vite/Vitest not picking up environment variables? #2117

@kevinmamaqi

Description

@kevinmamaqi

Describe the bug

I am trying to test a file that relies on environment variables, though it doesn't load them. I use vite+vitest with React.js. It works well on development/production, but when I test the component with the variable is undefined: import.meta.env.VITE_API_URL

When I initialize the test, it loads properly on my vite.config.js:

export default ({ mode }) => {
  process.env = { ...process.env, ...loadEnv(mode, process.cwd()) }
  console.log('mode', mode, loadEnv(mode, process.cwd())) <----- HERE IT APPEARS TO BE DEFINED WHEN THE TEST STARTS
  return defineConfig({
    base: '/',
    server: {
      port: 3000,
      proxy: {
        '/public': {
          target: `${process.env.VITE_API_URL}/`,
          changeOrigin: true,
        },
      },
    },
    publicDir: './public',
    plugins: [react()],
    test: {
      globals: true,
      environment: 'jsdom',
      setupFiles: './src/__test__/setup.js',
      include: ['./src/__test__/**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
    },
  })
}

Reproduction

  1. Create react app with vite-react template
  2. Add vitest
  3. Create .env with some environment variables
  4. Create a file that uses the variable
  5. Test the file and that the variable is present

Github repo: https://github.com/IT-Academy-BCN/ita-directory
Branch: https://github.com/IT-Academy-BCN/ita-directory/tree/511-test-recover-password
File: https://github.com/IT-Academy-BCN/ita-directory/blob/511-test-recover-password/frontend/src/__test__/pages/UserFlow/RecoverPassword.test.jsx

System Info

envinfo command not found

Used Package Manager

npm

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions