.env variables not available in jest testing environment

Viewed 35

When I run my code normally I can access my .env file with const newVar = process.env.MY_DOTENV_VARIABLE, but when I run jest everything becomes undefined. Is this normal for jest? If so, what is the best practice for storing variables?

Is it simply to create a set up file, eg:

// jest.config.ts
  setupFiles: [
    "<rootDir>/.jest/setEnvVars.ts",
  ],
# .env
  MY_DOTENV_VARIABLE=exampleString
1 Answers

I just needed to install dotenv. I think I got confused where process.env was working previously without the dotenv packaging. This was either due to me setting the env variables with scripts in my package.json file, eg "scripts":"NODE_ENV=test ..." and/or some packages were making changes. (I'm using various aws packages, and I've read that they can change environment variables)

Related