Reputation: 1864
BACKGROUND
I'm using process.env.<ENV NAME>
to set variables in some classes. I need to set them in the tests for the class variables to be set otherwise the test fails.
Currently, I'm setting the variables in a beforeAll()
hook. However, there are many test files in which I'll have to set these envs. I don't want to replicate this code throughout all these files if I don't have to.
I decided it would be a good idea to set them up prior to each test through a Jest set-up file. In jest.config.js
I added setupFiles: ['<rootDir>/jestSetupTest.js']
. Inside this file I added require('dotenv').config()
. The .env
file is in the root directory.
I've got test files in a couple of different directories: ./src/graphql/__tests__
and ./src/utils/__tests__
.
PROBLEM
The envs are being set but they are not being read by any of the Jest tests that are running.
ATTEMPTED
I looked into this issue which got me as far as being able to set-up the env vars, but it has nothing about issues using them.
I've added require('dotenv').config()
to the test files that use the envs, but that still doesn't work. This surprised me I thought at least this would set the envs.
I set --debug
on Jest but that doesn't show whether envs were set or not.
QUESTIONS
Does anyone know what is going on? Or how I can further diagnose this issue?
I get the impression envs can be set and used in Jest tests, as per the SO post above. Why am I not able to use them? Could it be a config issue with the way my files are set-up?
Upvotes: 0
Views: 1344
Reputation: 733
Maybe you already found a solution. I had my own struggles getting tests to run with the env variables from an .env.test
file for my 'create react app'. In the end, all that was necessary was to add the path to the desired env-file in my cmd line scripts in my package.json-file:
"test": "react-scripts test dotenv_config_path=.env.test",
No further configuration was needed.
But there could be some presets going on coming from 'create react app'. I am not entirely sure about this.
So, to get to your question: Maybe you could just put your env variables in a separate file witch you then load through your run-test-script.
Upvotes: 2